使用2d数组和JfreeChart制作散点图

时间:2011-07-06 10:12:33

标签: java jfreechart

这是我使用Java的第一个月,所以我提前为我的愚蠢问题道歉。我正在尝试使用Jfreechart制作一个简单的程序。我想在散点图上显示我的2D数组。 这是代码:


package myappthatusesjfreechart;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DefaultPieDataset;

public class MyAppThatUsesJFreeChart {

    public static void main(String[] args) {
        // create a dataset...
        int[][] a2 = new int[10][5];

        // print array in rectangular form
        for (int r = 0; r < a2.length; r++) {
            for (int c = 0; c < a2[r].length; c++) {
                System.out.print(" " + a2[r][c]);
            }
            System.out.println("");
        }

        // create a chart...
        JFreeChart chart = ChartFactory.createScatterPlot(
            "Scatter Plot", // chart title
            "X", // x axis label
            "Y", // y axis label
            a2, // data  ***-----PROBLEM------***
            PlotOrientation.VERTICAL,
            true, // include legend
            true, // tooltips
            false // urls
            );

        // create and display a frame...
        ChartFrame frame = new ChartFrame("First", chart);
        frame.pack();
        frame.setVisible(true);
    }
}

; ChartFactory.createScatterPlot;不允许我通过2d阵列,我想问有没有办法可以做到。

1 个答案:

答案 0 :(得分:11)

createScatterPlot()方法需要XYDataset,例如XYSeriesCollection。有使用XYSeriesCollection herehere的示例。

附录:这是一个更适合散点图的例子;只需在工厂调用中将a2替换为createDataset()

private static final Random r = new Random();

private static XYDataset createDataset() {
    XYSeriesCollection result = new XYSeriesCollection();
    XYSeries series = new XYSeries("Random");
    for (int i = 0; i <= 100; i++) {
        double x = r.nextDouble();
        double y = r.nextDouble();
        series.add(x, y);
    }
    result.addSeries(series);
    return result;
}