JavaFX Scatter Chart Example

In this JavaFX example, we will see how to create a Scatter Chart using JavaFX. 

A scatter chart is a set of points plotted on horizontal and vertical axes.

JavaFX Scatter Chart Example

In this JavaFX example, we use ScatterChart to display gold prices.

package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        initUI(stage);
    }

    private void initUI(Stage stage) {

        HBox root = new HBox();

        CategoryAxis xAxis = new CategoryAxis();
        NumberAxis yAxis = new NumberAxis("INR/10 gram", 40000, 60000, 10000);

        ScatterChart scatterChart = new ScatterChart<>(xAxis, yAxis);

        XYChart.Series data = new XYChart.Series<String, Number>();

        data.getData().add(new XYChart.Data<>("Jan 20", 43000));
        data.getData().add(new XYChart.Data<>("Mar 20", 45000));
        data.getData().add(new XYChart.Data<>("Jun 20", 42000));
        data.getData().add(new XYChart.Data<>("Jan 21", 48000));
        data.getData().add(new XYChart.Data<>("Aug 21", 50000));
        data.getData().add(new XYChart.Data<>("Dec 21", 52000));

        scatterChart.getData().add(data);
        scatterChart.setLegendVisible(false);

        Scene scene = new Scene(root, 500, 400);
        root.getChildren().add(scatterChart);

        stage.setTitle("Gold price in India");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Output:

Comments