面积图接受一系列数据点(x,y)作为输入值,使用一条线连接它们,并映射所获得的线和轴之间的区域。
StackedArea Chart是Area Chart的变体,在该图表中堆叠区域,以使每个系列相邻但不与之前的系列重叠。
在JavaFX中,您可以通过实例化javafx.scene.chart.StackedAreaChart类来创建堆积面积图。
在实例化此类时,必须传递Axis类的两个对象,它们代表x轴和y轴(作为构造函数的参数)。由于Axis类是抽象的,因此您需要传递其具体子类的对象NumberNumber(用于数字值)或CategoryAxis(字符串值)。
创建轴后,您可以使用setLabel()方法为其设置标签。
该XYChart.Series代表的一系列的数据项。您可以通过实例化该类为直线创建一系列点。此类包含一个可观察的列表,其中包含该系列中的所有点。
XYChart.Data表示在xy平面内的特定数据点。要创建一个点,您需要通过传递特定点的x和y值来实例化此类。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.stage.Stage;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.StackedAreaChart;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class StackedAreaChartExample extends Application {
public void start(Stage stage) {
//定义轴
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis(0, 30000, 5000);
yAxis.setLabel("Product Sales");
//创建面积图
StackedAreaChart<String, Number> areaChart = new StackedAreaChart(xAxis, yAxis);
//准备XYChart.Series对象
XYChart.Series series1 = new XYChart.Series();
series1.setName("Quarter1");
series1.getData().add(new XYChart.Data("Product A", 2898));
series1.getData().add(new XYChart.Data("Product B", 2577));
series1.getData().add(new XYChart.Data("Product C", 4566));
series1.getData().add(new XYChart.Data("Product D", 7689));
series1.getData().add(new XYChart.Data("Product E", 6788));
XYChart.Series series2 = new XYChart.Series();
series2.setName("Quarter2");
series2.getData().add(new XYChart.Data("Product A", 2768));
series2.getData().add(new XYChart.Data("Product B", 3687));
series2.getData().add(new XYChart.Data("Product C", 5656));
series2.getData().add(new XYChart.Data("Product D", 5658));
series2.getData().add(new XYChart.Data("Product E", 6790));
XYChart.Series series3 = new XYChart.Series();
series3.setName("Quarter3");
series3.getData().add(new XYChart.Data("Product A", 2342));
series3.getData().add(new XYChart.Data("Product B", 1898));
series3.getData().add(new XYChart.Data("Product C", 3455));
series3.getData().add(new XYChart.Data("Product D", 7689));
series3.getData().add(new XYChart.Data("Product E", 6788));
XYChart.Series series4 = new XYChart.Series();
series4.setName("Quarter4");
series4.getData().add(new XYChart.Data("Product A", 3123));
series4.getData().add(new XYChart.Data("Product B", 1978));
series4.getData().add(new XYChart.Data("Product C", 3454));
series4.getData().add(new XYChart.Data("Product D", 5686));
series4.getData().add(new XYChart.Data("Product E", 6790));
areaChart.getData().addAll(series1, series2, series3, series4);
//创建一个组对象
StackPane pane = new StackPane(areaChart);
//设置场景
Scene scene = new Scene(pane, 595, 300);
stage.setTitle("Stacked Area Chart");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出结果