简体   繁体   English

JavaFX LineChart:在图表中间插入新数据

[英]JavaFX LineChart: Insert new data in the middle of the chart

I'm using a line chart with JavaFX: 我正在使用JavaFX的折线图:

LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);

XYChart.Series series = new XYChart.Series();

lineChart.getData().add(series);

I want to add data to the series successively, thereby the order in which the values arrive can not be predicted. 我想连续地向该系列添加数据,从而无法预测值到达的顺序。 For example, the index can be between 0 and the current size of the series. 例如,索引可以在0和系列的当前大小之间。

series.getData().add(new XYChart.Data(index, value));

Consider the following scenario: 请考虑以下情形:

//initializing...
series.getData().add(new XYChart.Data(1, 400));
series.getData().add(new XYChart.Data(3, 500));
series.getData().add(new XYChart.Data(8, 100));
series.getData().add(new XYChart.Data(12, 120));
series.getData().add(new XYChart.Data(20, 300));

//later...
series.getData().add(new XYChart.Data(2, 450));
series.getData().add(new XYChart.Data(5, 300));
series.getData().add(new XYChart.Data(15, 200));

The problem is how the graph is depicted. 问题是如何描绘图表。 In the example above, at index 20 the graph makes a loop back to index 2. It looks like this: 在上面的示例中,在索引20处,图形循环回到索引2.它看起来像这样: 在此输入图像描述

But I want it to look like this: 但我希望它看起来像这样: 在此输入图像描述

What settings are necessary to update the graph properly without additional lines crossing the graph? 如果没有额外的线穿过图表,需要进行哪些设置才能正确更新图形?

I do something like this (my data is string, number). 我这样做(我的数据是字符串,数字)。 I can't help but thinking there must be a better way. 我不禁想到必须有更好的方法。 I've put this all in a method so I can just call addSorted(series,newData); 我把这一切都放在一个方法中,所以我可以调用addSorted(series,newData);

final Comparator<XYChart.Data<String, Number>> comparator = 
        (XYChart.Data<String, Number> o1, XYChart.Data<String, Number> o2) -> 
                o1.getXValue().compareTo(o2.getXValue());
lineChart.getData().get(0).getData().add(new XYChart.Data<>("2020", 1));
XYChart.Series newSeries = new XYChart.Series(lineChart.getData().get(0).getData().sorted(comparator));
lineChart.getData().add(0,newSeries);

There is a new answer to this problem with JavaFX 9. JavaFX 9对这个问题有了新的答案。

If you have JDK9, try 如果您有JDK9,请尝试

lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.X_AXIS);

(this is the default setting for JavaFX 9) (这是JavaFX 9的默认设置)

If you want for data to be plotted in the order it was added use: 如果要按照添加的顺序绘制数据,请使用:

lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.NONE);

See information here: http://download.java.net/jdk9/jfxdocs/javafx/scene/chart/LineChart.html#axisSortingPolicyProperty 请参阅此处的信息: http//download.java.net/jdk9/jfxdocs/javafx/scene/chart/LineChart.html#axisSortingPolicyProperty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM