4

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;
Steve
  • 4,457
  • 12
  • 48
  • 89

1 Answers1

6

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

trashgod
  • 203,806
  • 29
  • 246
  • 1,045