I'm using a line chart with 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.
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:
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);
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.
If you have JDK9, try
lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.X_AXIS);
(this is the default setting for 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
来源:https://stackoverflow.com/questions/21409270/javafx-linechart-insert-new-data-in-the-middle-of-the-chart