Skip to content
Advertisement

How would I create a JFreeChart scatterplot best fit line

I have an arraylist of points I want to include in a JFreeChart scatterplot. That works fine, but I now want a best fit line on it. After some searching, JFreeChart doesn’t support such calculations directly, so what I want to do is calculate it myself and then stick a line into the chart manually. How do I get a line in a scatterplot?

        XYSeries series = new XYSeries("Data");
        for (Point p : points) {
           series.add(p.getX(), p.getY());
        }
        XYSeriesCollection dataset = new XYSeriesCollection(series);
        JFreeChart chart = ChartFactory.createScatterPlot(chartName, "Mass", parameter, dataset, PlotOrientation.VERTICAL, false, true, true);
        return chart;

Advertisement

Answer

Use the built-in Regression method getOLSRegression(), seen here, or a statistical library such as Apache Commons Math to determine the slope and intercept of such a line using simple regression. Add your original data to a scatter plot, as shown here. Add an XYLineAnnotation representing the endpoints of your line, as shown here.

image

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement