JavaFX示例:创建包含负值的面积图
面积图接收一系列数据点 (x, y) 作为输入值,使用线连接它们,并映射所得线与轴之间的区域。在 JavaFX 中,您可以通过实例化 **javafx.scene.chart.AreaChart** 类来创建面积图。
实例化此类时,必须传递 Axis 类的两个对象,分别表示 x 轴和 y 轴(作为构造函数的参数)。由于 Axis 类是抽象类,因此您需要传递其具体子类的对象,例如 NumberAxis(用于数值)或 CategoryAxis(用于字符串值)。
包含负值的面积图
**XYChart.Data** 类表示图表中的数据点,您可以通过实例化此类来创建数据点。
XYChart.Data dataPoint1 = new XYChart.Data(x-value, y-value) XYChart.Data dataPoint2 = new XYChart.Data(x-value, y-value) XYChart.Data dataPoint3 = new XYChart.Data(x-value, y-value)
您可以传递负整数作为值(在数字轴上),当您这样做时,会在 0 处(相对)轴上绘制一条水平线,所有负值都绘制在其下方,所有正值都绘制在其上方。
创建所有所需的数据点后,您可以创建所需的系列,为此需要实例化 **XYChart.Series** 类并将数据点添加到其中。
XYChart.Series series = XYChart.Series series.getData().add(dataPoint1); series.getData().add(dataPoint2); series.getData().add(dataPoint3);
您可以根据需要创建任意数量的此类系列。
示例
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.chart.AreaChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.layout.StackPane; public class AreaCharts_NegativeValues extends Application { public void start(Stage stage) { //Defining the x and y axes CategoryAxis xAxis = new CategoryAxis(); NumberAxis yAxis = new NumberAxis(-5, 7.5, 2.5); //Setting labels for the axes yAxis.setLabel("Values"); //Creating an area chart AreaChart<String, Number> areaChart = new AreaChart<String, Number>(xAxis, yAxis); //Preparing the data points for the series1 XYChart.Series series1 = new XYChart.Series(); series1.getData().add(new XYChart.Data("Apples", 2)); series1.getData().add(new XYChart.Data("Oranges", -2)); series1.getData().add(new XYChart.Data("Pears", -3)); series1.getData().add(new XYChart.Data("Grapes", 2)); series1.getData().add(new XYChart.Data("Bananas", 1)); //Preparing the data points for the series3 XYChart.Series series2 = new XYChart.Series(); series2.getData().add(new XYChart.Data("Apples", 2)); series2.getData().add(new XYChart.Data("Oranges", 4)); series2.getData().add(new XYChart.Data("Pears", 4)); series2.getData().add(new XYChart.Data("Grapes", -2)); series2.getData().add(new XYChart.Data("Bananas", 5)); //Setting the name to all the series series1.setName("John"); series2.setName("Jane"); //Setting the data to area chart areaChart.getData().addAll( series1, series2); //Creating a stack pane to hold the chart StackPane pane = new StackPane(areaChart); pane.setPadding(new Insets(15, 15, 15, 15)); pane.setStyle("-fx-background-color: BEIGE"); //Setting the Scene Scene scene = new Scene(pane, 595, 350); stage.setTitle("Area Chart"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出
广告