Monday, June 27, 2016

82. ScatterChart

A Scatter graph, like all XY graphs, needs xAxis and yAxis. We can have any number of series to plot. Here we use two series.


We define three points (for each of the two series), set a title and remove the vertical zero line. You can comment out the setVerticalZeroLineVisible to see what it does, or set it to true.


package ex82;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class Ex82 extends Application {
 
    ObservableList<XYChart.Series<Integer, Double>> obList 
            = FXCollections.observableArrayList();
    
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        NumberAxis xAxis = new NumberAxis();
        xAxis.setAutoRanging(false);
        xAxis.setLowerBound(-1);
        xAxis.setUpperBound(3);
        xAxis.setTickUnit(1);
        NumberAxis yAxis = new NumberAxis();
        initData();
        ScatterChart scatterChart=new ScatterChart(xAxis,yAxis,obList);
        scatterChart.setVerticalZeroLineVisible(false);
        scatterChart.setTitle("A scatter plot");
        
        StackPane root = new StackPane();
        root.getChildren().add(scatterChart);
        
        primaryStage.setTitle("Example 82. ScatterChart");
        primaryStage.setScene(new Scene(root, 400, 250));
        primaryStage.show();
    }
 
    private void initData() {
        Series series1 = new Series<>();
        Series series2 = new Series<>();
        series1.getData().addAll(
                new XYChart.Data(0, 5),
                new XYChart.Data(1, 3),
                new XYChart.Data(2, 2)
                );
        series1.setName("series 1");
        series2.getData().addAll(
                new XYChart.Data(0, 2),
                new XYChart.Data(1, 4),
                new XYChart.Data(2, 7)
                );
        series2.setName("series 2");
        obList.addAll(series1, series2);
    }
}

This is the output:


No comments:

Post a Comment