Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

java - Making a Scatter Plot Using 2d array and JfreeChart

This is my First Month with Java, so I apologize for my stupid question in advance. I'm trying to make a simple program using Jfreechart. I want to display my 2D array on the scatter plot. here is the code:


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);
    }
}

The ;ChartFactory.createScatterPlot; is not allowing me to pass the 2d array, I want to ask is there any way that i can do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The createScatterPlot() method expects an XYDataset, such as XYSeriesCollection. There are examples using XYSeriesCollection here and here.

Addendum: Here's an example more suited to a scatter plot; just replace a2 with createDataset() in the factory call.

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...