如何在 Java 中更改图表比例

How to change diagram Scale in Java

我有一个图表,其中 x 轴显示时间,y 轴显示我的数据。 我想通过为 x 轴选择不同的指标来更改比例。例如秒、分和小时刻度。默认是第二个。因此,如果我选择分钟,图表应该更小并且更弯曲。任何的想法? UI 未完成,但您假设会有 x 和 y 轴。参数 degree 决定它应该缩放到秒(degree=1), 分钟(度数=60)或小时(度数=3600)

private void drawLines(Graphics g, ArrayList<Point> points,int degree) throws Exception {

    if (points == null || points.isEmpty()) {
        throw new Exception("No points found!!!");
    }

    for (int i = 0; i < points.size() - 1; i++) {

        Point firstPoint = points.get(i);
        Point secondPoint = points.get(i + 1);

        g.drawLine((int) firstPoint.getX(), (int) firstPoint.getY(), (int) secondPoint.getX(),
                (int) secondPoint.getY());
    }

}

考虑使用 , which scales the graph to fill the enclosing container. In the example seen here,封闭容器是一个 ChartPanel,它被添加到框架默认 BorderLayoutCENTER 中。这将允许图形随着封闭框架的大小调整而增大和缩小。

一般方案使用 linear interpolation. Given the following proportions, you can cross-multiply and solve for the missing coordinate, as shown in this complete example 将鼠标坐标映射到图像中的像素坐标来映射模型和视图坐标。

view.x : panelWidthInPixels :: model.x : modelXRange
view.y : panelHeightInPixels :: model.y : modelYRange

I do not want to use the JFreeChart. Is there any other way?

是的,作为@MadProgrammer ,你可以

  • 使用上面显示的比例将数据缩放到封闭容器。 example cited isolates the basic approach; JFreeChart 是一个完整的示例。

  • 使用 BufferedImage 将渲染图像缩放到封闭容器。此 example's ComponentHandler 绘制成 BufferedImage,其大小可填充封闭的 JPanelbackground 图像在 paintComponent() 的实现中呈现。调整框架大小以查看效果。

  • 使用应用于图形上下文的变换将渲染图像缩放到封闭容器。典型示例显示 here and here.