我在 JavaFX 中使用条形图和折线图。当我使两个图表大小相同并将它们放在同一位置时,它们完美地相互重叠。我如何使折线图显示在条形图的顶部。
目前我已将它们的不透明度设置为 0.7,这样它们“看起来不错”,但显然这不是正确的方法。
最佳答案
Jewelsea 发布了 example on a gist .
它基本上归结为使用 StackPane 来堆叠图表并修改所有叠加层的可见性。
这是一个更简单的修改版本,我如何使用它:
public class StackedChartSample extends Application {
final static String austria = "Austria";
final static String brazil = "Brazil";
final static String france = "France";
final static String italy = "Italy";
final static String usa = "USA";
@Override
public void start(Stage stage) {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
// base chart
final BarChart<String, Number> barChart = new BarChart<String, Number>(xAxis, yAxis);
barChart.setLegendVisible(false);
barChart.setAnimated(false);
xAxis.setLabel("Country");
yAxis.setLabel("Value");
// overlay chart
LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);
lineChart.setLegendVisible(false);
lineChart.setAnimated(false);
lineChart.setCreateSymbols(true);
lineChart.setAlternativeRowFillVisible(false);
lineChart.setAlternativeColumnFillVisible(false);
lineChart.setHorizontalGridLinesVisible(false);
lineChart.setVerticalGridLinesVisible(false);
lineChart.getXAxis().setVisible(false);
lineChart.getYAxis().setVisible(false);
lineChart.getStylesheets().addAll(getClass().getResource("chart.css").toExternalForm());
barChart.getData().add( createChartSeries());
lineChart.getData().add( createChartSeries());
StackPane root = new StackPane();
root.getChildren().addAll( barChart, lineChart);
Scene scene = new Scene(root, 800, 600);
stage.setScene(scene);
stage.show();
}
private XYChart.Series<String,Number> createChartSeries() {
XYChart.Series<String,Number> series = new XYChart.Series<String,Number>();
series.getData().add(new XYChart.Data<String,Number>(austria, 25601.34));
series.getData().add(new XYChart.Data<String,Number>(brazil, 20148.82));
series.getData().add(new XYChart.Data<String,Number>(france, 10000));
series.getData().add(new XYChart.Data<String,Number>(italy, 35407.15));
series.getData().add(new XYChart.Data<String,Number>(usa, 12000));
return series;
}
public static void main(String[] args) {
launch(args);
}
}
图表.css
.chart-plot-background {
-fx-background-color: transparent;
}
.default-color0.chart-series-line {
-fx-stroke: blue;
}
.default-color0.chart-line-symbol {
-fx-background-color: blue, white;
}
关于javafx - JavaFX 中的堆叠图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28788117/