如何使用两个数组绘制 XYLineChart 图形:一个用于 x 和 y 坐标



如何使用JFreeChart绘制具有两个数组的折线图:一个用于x坐标,另一个用于y坐标。我有两个函数,给了我两个数组。我想用该数组绘制折线图,是否有任何可能的方法可以做到这一点。

XYSeries series = new XYSeries(" "); 
for(int i=((fIndex-1)*2);i<=((tIndex*2)-1);i+=2)
{
    series.add(xTValue[i],yTValue[i]);
} 
XYSeriesCollection dataset = new XYSeriesCollection(); 
dataset.addSeries(series); 
return dataset;

我可以按照上面的代码执行此操作吗?

您可以使用

XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series = new DefaultXYSeries();
series.addSeries(" ", new double[][]{xTValue,yTValue});
dataset.addSeries(series);
JFreeChart chart = ChartFactory.createXYLineChart("My chart title", 
        "my x-axis label", "my y-axis label", dataset);

或者,如果您不需要特别需要XYLineChart,那么您可以通过子类化FastScatterPlot来做到这一点(我知道您想要线图,但这是一种简单的方法 - 您覆盖render()方法来绘制线条!),如下所示:

public class LinePlot extends FastScatterPlot {
    private float[] x, y;
    public LinePlot(float[] x, float[] y){
        super();
        this.x=x;
        this.y=y;
    }
    @Override
    public void render(final Graphics2D g2, final Rectangle2D dataArea,
        final PlotRenderingInfo info, final CrosshairState crosshairState) {
        // Get the axes
        ValueAxis xAxis = getDomainAxis();
        ValueAxis yAxis = getRangeAxis();
        // Move to the first datapoint
        Path2D line = new Path2D.Double();
        line.moveTo(xAxis.valueToJava2D(x[0], dataArea, RectangleEdge.BOTTOM),
                yAxis.valueToJava2D(y[0], dataArea, RectangleEdge.LEFT));
        for (int i = 1; i<x.length; i++){
            //Draw line to next datapoint
            line.lineTo(aAxis.valueToJava2D(x[i], dataArea, RectangleEdge.BOTTOM),
                    yAxis.valueToJava2D(y[i], dataArea, RectangleEdge.LEFT));
        }
        g2.draw(line);
    }
}

这是一个相当简单的实现 - 例如,没有检查x和y具有相同数量的点,也没有添加颜色等(例如 g2.setPaint(myPaintColour)或线型(例如 g2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10.0f, new float[] { 7, 3, 1, 3 }, 0.0f))会交替给出-•-•型线)

相关内容

最新更新