Creating Time Series Chart With JFree Chart

In this basic tutorial, I will teach you how to create a simple timeseries chart in Java using the free JFreeChart. The program uses the following two jar files, and they come with the JFreeChart itself. You can download JFreeChart at their official website www.jfreechart.org

  • jcommon-1.0.15.jar
  • jfreechart-1.0.12.jar

The program also demonstrates how easily you can save a generated chart to your computer using the Charts Utilities from JFreeChart

package com.kushal.utilities;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

public class TimeSeriesChartDemo {

	public void createTimeSeriesXYChart()
	{

		TimeSeries series = new TimeSeries( "", Day.class );

		series.add(new Day(new Date("2009/01/01")), 123);
		series.add(new Day(new Date("2009/01/02")), 133);
		series.add(new Day(new Date("2009/01/03")), 99);
		series.add(new Day(new Date("2009/01/04")), 113);
		series.add(new Day(new Date("2009/01/05")), 159);
		series.add(new Day(new Date("2009/01/06")), 124);
		series.add(new Day(new Date("2009/01/07")), 120);

        TimeSeriesCollection dataset=new TimeSeriesCollection();
        dataset.addSeries(series);

        JFreeChart chart = ChartFactory.createTimeSeriesChart
        ("User Participation Chart", 	// Title
         "Day",              		// X-Axis label
         "Number Of Users",             // Y-Axis label
         dataset,         		// Dataset
         true,                     	// Show legend
         true,				//tooltips
         false				//url
        );

        saveChart(chart);

	}

	public void saveChart(JFreeChart chart)
	{
		String fileName="C:/Users/kushal/Desktop/myTimeSeriesChart.jpg";
		try {
			/**
			 * This utility saves the JFreeChart as a JPEG
			 * First Parameter: FileName
			 * Second Parameter: Chart To Save
			 * Third Parameter: Height Of Picture
			 * Fourth Parameter: Width Of Picture
			 */
            ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
        } catch (IOException e) {
        	e.printStackTrace();
            System.err.println("Problem occurred creating chart.");
        }
	}
	public static void main(String args [])
	{
		new TimeSeriesChartDemo().createTimeSeriesXYChart();

	}

}


The following is the output of this program