Tuesday, June 28, 2016

85. StackedBarChart

The StackedBarChart is very similar to the BarChart except now the all heights are on one bar.


Thus we only have one bar for a category, no matter how many series. Since we have 3 categories here, there are only 3 bars.


package ex85;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.StackedBarChart;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class Ex85 extends Application {
 
    ObservableList<XYChart.Series> obList 
            = FXCollections.observableArrayList();
    
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        CategoryAxis xAxis = new CategoryAxis();
        NumberAxis yAxis = new NumberAxis();
        initData();
        StackedBarChart stackedBarChart = 
                new StackedBarChart(xAxis, yAxis, obList);
        stackedBarChart.setTitle("A StackedBar plot");
        
        StackPane root = new StackPane();
        root.getChildren().add(stackedBarChart);
        
        primaryStage.setTitle("Example 85. StackedBarChart");
        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