Simple Linear Regression with JFreeChart
I’m sure there are numerous ways you can graph a simple linear regression using JFreeChart. Wanting to do so, I turned to Google and came across a few implementations. However, as none of them seemed terribly well written, I took a stab at it myself.
Basically, what I wanted was a scatter plot with the regressed line on top of it. As a bonus, I set out to include support for multiple data sets in one graph. JFreeChart allows you to combine data sets and create overlaid charts, so the whole thing was surprisingly easy. After looking at a few examples, I came up with the following:

- Simple linear regression example
Pretty nifty, huh? So, here’s how it’s done …
We start by creating a scatter plot from one or more series of data. The
ChartFactory.createScatterPlot()method does exactly that, so I won’t elaborate on it here.Next, we add a second data set to the plot. It will be used to render the regressed line and in fact consists of only two points per series: the end points of the line segment that will be drawn.
Obviously, JFreeChart already contains the functionality to draw line charts. Hence, all we need to draw the lines is a simple
StandardXYItemRenderer. Thus, we create an instance of that class and associate it with the second data set.And finally, some cosmetic surgery. Since JFreeChart does not know the scatter plot and line chart are related, it will paint associated series in a different color. Using
setSeriesPaint(), however, we can easily match both renderers’ color schemes.The result is a standard
JFreeChart, which can be customized and visualized like any other one.
And that really is all there is to it. The resulting code can be found in RegressionDemo, which I am releasing under a GPL license. Enjoy.
Update: You’ll probably want to get rid of superfluous legend items. To do that, just tell JFreeChart that you want to hide them:
regressionRenderer.setBaseSeriesVisibleInLegend(false);
I took the liberty of updating the screenshot and code to reflect this.