带有分类轴的 JavaFX 折线图示例
内联图表,数据值表示一系列由线连接的点。在 JavaFX 中,可以通过实例化 **javafx.scene.chart.LineChart** 类来创建折线图。
在实例化此类时,你必须传递表示 x 和 y 轴的 Axis 类(作为构造函数的参数)的两个对象。由于 Axis 类是抽象的,因此你需要传递它的具体子类的对象:NumberAxis(对于数值)或 CategoryAxis(字符串值)。
示例
以下是演示如何使用分类轴的示例。在此,我们正在绘制 OnePlus 手机各种型号的销量,我们使用分类(x)轴来绘制手机型号。
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.layout.StackPane; public class LineChart_Category extends Application { public void start(Stage stage) { //Defining the x an y axes CategoryAxis xAxis = new CategoryAxis(); NumberAxis yAxis = new NumberAxis(200, 600, 100); //Setting labels for the axes xAxis.setLabel("Model"); yAxis.setLabel("Price (USD)"); //Creating a line chart LineChart linechart = new LineChart(xAxis, yAxis); //Preparing the data points for the line XYChart.Series series = new XYChart.Series(); series.getData().add(new XYChart.Data("OnePlus X", 249)); series.getData().add(new XYChart.Data("OnePlus One", 299)); series.getData().add(new XYChart.Data("OnePlus 2", 329)); series.getData().add(new XYChart.Data("OnePlus 3", 399)); series.getData().add(new XYChart.Data("OnePlus 3T", 439)); series.getData().add(new XYChart.Data("OnePlus 5", 479)); series.getData().add(new XYChart.Data("OnePlus 5T", 499)); series.getData().add(new XYChart.Data("OnePlus 6", 559)); //Setting the name to the line (series) series.setName("Price of mobiles"); //Setting the data to Line chart linechart.getData().add(series); //Creating a stack pane to hold the chart StackPane pane = new StackPane(linechart); pane.setPadding(new Insets(15, 15, 15, 15)); pane.setStyle("-fx-background-color: BEIGE"); //Setting the Scene Scene scene = new Scene(pane, 595, 300); stage.setTitle("Line Chart"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出
广告