Home » Tools » Creating TimeSeries chart with jfreechart

Creating TimeSeries chart with jfreechart

Second chart generated by Mavis – chart with my yearly activities with games and books, by each month. As previously described bar chart I use jfreechart to generate data.

As with bar chart to create basic time series plot we need to create dataset and then pass it to ChartFactory object. Difference is all about creating dataset: TimeSeriesCollection contains multiple lists – each aggregates values for values over time period. Single entry inside them stores value for one date. So for example:

TimeSeries books = new TimeSeries("Books");
for(int i=1; i<13; ++i){
	Month currentMonth = new Month(i,yearToPlot);

TimeSeriesCollection dataset = new TimeSeriesCollection();

JFreeChart chart = ChartFactory.createTimeSeriesChart(

At first I create series for data on given subject - books instance of TimeSeries. Then populate it with method add, which requires date and proper value, that can be converted to double. We create TimeSeriesCollection instance for dataset and add books series into it. Lastly we pass it to createTimeSeriesChart method of ChartFactory.

How to add another series?
As I mentioned before TimeSeriesCollection serves as list of lists that collects values over time period. So to add another series we must create and populate another TimeSeries instance, and then add it to TimeSeriesCollection. It's worth to mention that String passed to TimeSeries instance acts as series name for chart legend.
So plot line showing data from:

TimeSeries devposts = new TimeSeries("Dev posts")

Will be described as "Dev posts".

Example chart:

Changing date display format for TimeSeriesChart ?

It's similar to changing scale for bar charts.
At first we must get ahold of domain axis instance:
First we must get XYPlot, which is used by TimeSeriesPlot as chart object.

XYPlot plot = chart.getXYPlot();

And then get from it domain axis and set proper Unit Tick and it's Format.

DateAxis xaxis = (DateAxis) plot.getDomainAxis();
xaxis.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH, 1));
xaxis.setDateFormatOverride(new SimpleDateFormat("MMM"));
Posted in Tools and tagged as , ,

Comments are closed.