如何在 JavaFX LineChart 的 NumberAxis 上保持相等的 x 和 y 长度?

How to maintain equal x and y length on the NumberAxis in JavaFX LineChart?

我正在使用 NumberAxis 创建笛卡尔坐标图以在折线图中创建 x 轴和 y 轴,并使用 getDisplayPosition 查找沿 x 轴的两点与沿 y 轴的两点之间的距离。 差异并不相等

我将 upper/lower x 轴和 y 轴的边界设置为与相同的 tickUnit 设置相同。从视觉上看,网格看起来正方形且四面都相等,但我似乎无法使它们完全相等。

以下是我在折线图中为 x 和 y 设置 NumberAxis 的方法:

xAxis.setLowerBound(-2.4);
xAxis.setUpperBound(2.4);
xAxis.setTickUnit(.1);
xAxis.setSide(Side.BOTTOM);
xAxis.setAutoRanging(false);

yAxis.setLowerBound(-2.4);
yAxis.setUpperBound(2.4);
yAxis.setTickUnit(.1);
yAxis.setSide(Side.LEFT);
yAxis.setAutoRanging(false);

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

下面是我如何转换输入以正确显示矩形

private Rectangle calcRectangle(SectionRectangle rectangle){
        double xPosition = xAxis.getDisplayPosition(rectangle.getXorigin()); 
        double yPosition = yAxis.getDisplayPosition(rectangle.getYorigin());
        double xCoord = xPosition + chartZeroX;//x origin of rectangle 
        double yCoord = yPosition + chartZeroY;//y origin of rectangle

        double width = rectangle.getXorigin() + rectangle.getWidth();

        double widthPosition = xAxis.getDisplayPosition(width);
        double heightPosition = yAxis.getDisplayPosition(rectangle.getYorigin() + rectangle.getHeight());

        Rectangle calculatedRectangle = new Rectangle(xCoord, yCoord - (yPosition - heightPosition), widthPosition - xPosition, yPosition - heightPosition);

        calculatedRectangle.setFill(Color.TRANSPARENT);

        Rotate rotate = new Rotate();
        rotate.setAngle(360 - rectangle.getRotation());
        rotate.setPivotX(xPosition + chartZeroX);
        rotate.setPivotY(yPosition + chartZeroY);
        calculatedRectangle.getTransforms().add(rotate);
        calculatedRectangle.setStroke(Color.BLACK);

        return calculatedRectangle;

这是我将形状添加到图形上的方法

Pane chartContent = (Pane) linechart.lookup(".chart-content");
Rectangle rectangle = calcRectangle(rectangleData);
chartContent.getChildren().add(rectangle);

如果不旋转,矩形将按预期比例显示,但由于像素宽度与像素高度的微小差异,旋转 90 度会导致矩形的高度大于宽度。

这里有一个更准确的问题示例

double xdiff = xAxis.getDisplayPosition(1) - xAxis.getDisplayPosition(0);
double ydiff = yAxis.getDisplayPosition(0) - yAxis.getDisplayPosition(1);

此处 xdiff = 195.208 和 ydiff = 191.041

希望有某种方法可以强制 x 轴和 y 轴保持完全相等的距离。

我通过控制折线图的高度和宽度解决了我自己的问题:

linegraph.setPrefHeight(850);
linegraph.setMinHeight(850);
linegraph.setMaxHeight(850);
linegraph.setMinWidth(853);
linegraph.setMaxWidth(853);
linegraph.setPrefWidth(853);
linegraph.setPrefSize(853, 850);
linegraph.setMinSize(853, 850);
linegraph.setMaxSize(853, 850);

我使用以下方法检查了 x=0、x=1 和 y=0、y=1 之间的距离:

double xlength = xAxis.getDisplayPosition(1) - xAxis.getDisplayPosition(0);
double ylength = yAxis.getDisplayPosition(0) - yAxis.getDisplayPosition(1);

我慢慢增加宽度,直到两个长度相等。