下面列出了怎么用javafx.scene.chart.Chart的API类实例代码及写法,或者点击链接到github查看源代码。
public static Chart plotFunction(List<Function<Double, Double>> functions, Number xStart, Number xEnd) {
int div = 500;
double x0 = xStart.doubleValue();
double x1 = xEnd.doubleValue();
double step = 1./div* (x1-x0);
Axis<Number> xAxis = new NumberAxis(x0, x1, .1* (x1-x0));
Axis<Number> yAxis = new NumberAxis();
ObservableList<XYChart.Series<Number, Number>> series = FXCollections.observableArrayList();
LineChart<Number,Number> chart = new LineChart(xAxis, yAxis, series);
chart.setCreateSymbols(false);
for (Function<Double, Double> f: functions) {
XYChart.Series<Number, Number> mainSeries = new XYChart.Series();
series.add(mainSeries);
ObservableList<XYChart.Data<Number, Number>> data = FXCollections.observableArrayList();
mainSeries.setData(data);
for (double x = x0; x < x1; x= x +step) {
final Number y = f.apply(x);
data.add(new XYChart.Data<>(x,y));
}
}
return chart;
}
public TrainingView() {
label = new Label();
Button button = new Button("train network model");
button.setOnAction(e -> {
Task task = train();
button.disableProperty().bind(task.runningProperty());
});
series = new Series();
series.setName("#iterations");
Chart chart = createChart(series);
VBox controls = new VBox(15.0, label, button, chart);
controls.setAlignment(Pos.CENTER);
setCenter(controls);
}
@Override
public void start(Stage stage) throws Exception {
Function<Double, Double> classic = b -> Math.exp(Math.pow(64./9.*b* Math.log(b)*Math.log(b), 1./3));
Function<Double, Double> shor = b-> Math.pow(b,3.);
List<Function<Double,Double>> functions = Arrays.asList(classic, shor);
Chart chart = plotFunction(functions, 0.000001, 20);
Scene scene = new Scene(chart, 640, 480);
stage.setScene(scene);
stage.show();
}
/**
* Generates the chart and writes to an image.
*
* @param chart to be rendered
* @param width with of the chart in pixels
* @param height height of the chart in pixels
* @param fileName of the written image
* @param styleSheet A custom stylesheet to be applied to the charts
*/
private void genChart(Chart chart, int width, int height, String fileName, String styleSheet) {
Platform.runLater(() -> {
Scene scene = new Scene(chart, width, height);
if (styleSheet != null && !styleSheet.isEmpty()) {
scene.getStylesheets().add(styleSheet);
}
WritableImage img = new WritableImage(width, height);
scene.snapshot(img);
writeImage(img, fileName);
});
}
private Chart createChart(Series<Integer, Double> series) {
NumberAxis xAxis = new NumberAxis();
xAxis.setUpperBound(620d);
xAxis.setMinorTickCount(25);
xAxis.setTickUnit(100);
xAxis.setAutoRanging(false);
NumberAxis yAxis = new NumberAxis();
LineChart answer = new LineChart(xAxis, yAxis);
answer.setTitle("score evolution");
answer.setCreateSymbols(false);
ObservableList<XYChart.Series<Integer, Double>> data = FXCollections.observableArrayList();
data.add(series);
answer.setData(data);
return answer;
}