Charts: How to correlate colors between charts?

后端 未结 2 1184
南旧
南旧 2021-01-06 04:38

Below is an example that

  • has two charts visualizing the same set of data
  • while the data are the same, their sequence differs (in rw code that would ha
2条回答
  •  既然无缘
    2021-01-06 05:13

    I just changed some stuff in the start method (plus some imports I'm sure). I don't think this is the best way. I would make a stylesheet in user.dir and write my colors there with names like java-color etc., then use that for the default chart colors.

    @Override
    public void start(Stage primaryStage) {
        PieChart pieChart = new PieChart();
        pieChart.setData(getPieData());
        final HashMap colors = new HashMap<>();
        pieChart.getData().stream().forEach((pd)->{
            colors.put(pd.getName(), pieChart.getData().indexOf(pd));
        });
    
        final CategoryAxis xAxis = new CategoryAxis(FXCollections.observableArrayList("none"));
        final NumberAxis yAxis = new NumberAxis();
        final StackedBarChart sbc =
                new StackedBarChart<>(xAxis, yAxis);
        ObservableList> barData = createBarData(getPieData());
        // simulate client code that re-orders/filters the data
        FXCollections.shuffle(barData);
        sbc.setData(barData);
    
        primaryStage.setTitle("Correlated Charts");
        Scene scene = new Scene(new HBox(pieChart, sbc));
        primaryStage.setScene(scene);
        primaryStage.show();
    
        //can only get nodes after charts are drawn
        barData.stream().forEach((bd)->{
            int num = colors.get(bd.getName());
            //eg. chart-bar series1 data0 default-color1
            bd.getData().get(0).getNode().getStyleClass().setAll("chart-bar","series"+num,"data0","default-color"+num);
        });
    
        Legend legend = (Legend)sbc.lookup(".chart-legend");
        legend.getChildrenUnmodifiable().stream().forEach((l)->{
            Label label = (Label)l;
            Node n = label.getGraphic();
            int num = colors.get(label.getText());
            //eg. chart-legend-item-symbol chart-bar series1 bar-legend-symbol default-color1
            n.getStyleClass().setAll("chart-legend-item-symbol","chart-bar","series"+num,"bar-legend-symbol","default-color"+num);
        });
    }
    

    here's proof

提交回复
热议问题