JavaFX 折线图由绘图区和轴组成。由于轴渲染使用一些显示空间,因此原点在折线图中的位置不是 (0, 0)。如何获得相对于折线图本身位置的此位置?
我想计算绘图区域中一个点相对于折线图位置的位置。x 轴和 y 轴的getDisplayPosition
方法相对于原点提供了这一点,但我没有看到获取原点位置的明显方法。
更好的观察方法是通过chart.lookup
命令获取绘图区域,如下所示:
//gets the display region of the chart
Node chartPlotArea = chart.lookup(".chart-plot-background");
double chartZeroX = chartPlotArea.getLayoutX();
double chartZeroY = chartPlotArea.getLayoutY();
axis.getDisplayPosition(val)
方法提供给定轴val
在绘图区域中相对于绘图区左上角的像素位置。您可以使用 getDisplayPosition() 方法计算任何点相对于折线图原点的位置。请记住,调整折线图大小时,这些像素位置会有所不同。
@Override
public void start(Stage stage) {
stage.setTitle("Line Chart Sample");
//defining the axes
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Number of Month");
//creating the chart
final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
//defining a series
XYChart.Series series = new XYChart.Series();
series.setName("My portfolio");
//populating the series with data
series.getData().add(new XYChart.Data(-1, 4));
series.getData().add(new XYChart.Data(0, 2));
series.getData().add(new XYChart.Data(1, -2));
series.getData().add(new XYChart.Data(5, 1));
Scene scene = new Scene(lineChart, 800, 400);
lineChart.getData().add(series);
System.out.println("");
stage.setScene(scene);
stage.show();
System.out.println("Points in linechart -> Pixel positions relative to the top-left corner of plot area: ");
System.out.println("(0,0) -> " + getFormatted(xAxis.getDisplayPosition(0), yAxis.getDisplayPosition(0)));
// Same as
// System.out.println("(0,0) " + getFormatted(xAxis.getZeroPosition(), yAxis.getZeroPosition()));
System.out.println("(-1,4) -> " + getFormatted(xAxis.getDisplayPosition(-1), yAxis.getDisplayPosition(4)));
System.out.println("(1,-2) -> " + getFormatted(xAxis.getDisplayPosition(1), yAxis.getDisplayPosition(-2)));
System.out.println("(-1.5,5) origin of plot area -> " + getFormatted(xAxis.getDisplayPosition(-1.5), yAxis.getDisplayPosition(5)));
System.out.println("Note: These pixel position values will change when the linechart's size is n changed through window resizing for example.");
}
private String getFormatted(double x, double y) {
return "[" + "" + x + "," + y + "]";
}