Skip to main content

Example to draw “Time Series Line Chart” using jfreechart in Java

A very good example of “Time Series Chart” is available here :

I am writing this example to explore it further means to describe which settings you can change as per your requirements. I have tried my best to document everything. Please let me know if you have any questions after going through the code. Let's start...

//Code Starts here
 * To change this template, choose Tools | Templates
 * and open the template in the editor.

package jfreecharts;

 * @author sshankar

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Stroke;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickMarkPosition;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

 * A demo.

public class TimeSeriesChart extends ApplicationFrame {

     * A demo.
     * @param title  the frame title.
    public TimeSeriesChart(final String title) {

        final XYDataset dataset = createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(800, 600));
        chartPanel.setMouseZoomable(true, false);
        this.add(chartPanel, BorderLayout.CENTER);
        JPanel customPanel = new JPanel();
        JButton saveButton = new JButton("Save Graph as Image");

        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    //Code to display save dialog box
                    String graph_file_name = "";
                    final JFrame frame = new JFrame();
                    JFileChooser chooser = new JFileChooser();

                    //Code to select files of .jpg extention only
                    ExampleFileFilter filter = new ExampleFileFilter();
                    filter.setDescription("JPEG image");
                    int choice = 0;
                        choice = chooser.showSaveDialog(frame);
                    }while(choice != JFileChooser.APPROVE_OPTION);

                    graph_file_name = chooser.getSelectedFile().getAbsolutePath();
                    //code to find if extension is already given with file name or not
                    String fileName = graph_file_name;
                    String ext      = "";
                    int mid= fileName.lastIndexOf(".");
                    if(mid > 0){
                        ext   = fileName.substring(mid+1,fileName.length()); 
                    if(!(ext != null && !ext.trim().isEmpty() && ext.length() != 0)) {
                        graph_file_name = graph_file_name+".jpg";
                    // Save as JPEG
                    ChartUtilities.saveChartAsJPEG(new File(graph_file_name), chart, 800, 600);
                    JOptionPane.showMessageDialog(null,"Image Saved Successfully.", "Information", JOptionPane.INFORMATION_MESSAGE);
                }catch(Exception ex){
                    JOptionPane.showMessageDialog(null,"Please try again", "Information", JOptionPane.INFORMATION_MESSAGE);
         this.add(customPanel, BorderLayout.SOUTH);

     * Creates a chart.
     * @param dataset  a dataset.
     * @return A chart.
    private JFreeChart createChart(final XYDataset dataset) {

        final JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "Sample Chart",

        chart.setBackgroundPaint(Color.LIGHT_GRAY);//light gray
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(new Color(0xffffe0));
        final XYItemRenderer xyitemrenderer  = plot.getRenderer();
        if (xyitemrenderer  instanceof XYLineAndShapeRenderer) {
            final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyitemrenderer;
            renderer.setShapesVisible( true );
            renderer.setDrawOutlines( true );
            //sets the joint level size means the dot size which join two points on a graph 2f,3f
            Stroke stroke = new BasicStroke(
            3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
        final DateAxis xaxis = (DateAxis) plot.getDomainAxis();
         //Change domain axis lable by 180/4=45 degree
        //axis.setLabelAngle(Math.PI / 4.0);
        //Sets the Tick Labels means domain value labels by 90 degree
        //Try to play with it. It will work only in case of  horizontal tick mark
        //set date format
        xaxis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss MM-dd-yy"));
        final NumberAxis yaxis = (NumberAxis) plot.getRangeAxis();
        //To set range values integer only. Default are float
        return chart;

     * Creates a sample dataset.
     * @return the dataset.
    private XYDataset createDataset() {

        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        final TimeSeries s1 = new TimeSeries("Series 1", Second.class);
        s1.add(new Second(0, 0, 0, 7, 7, 2012), 12);
        s1.add(new Second(0, 30, 2, 7, 7, 2012), 31);
        s1.add(new Second(0, 15, 12, 7, 7, 2012), 80);
        final TimeSeries s2 = new TimeSeries("Series 2", Second.class);
        s2.add(new Second(0, 20, 3, 7, 7, 2012), 50);
        s2.add(new Second(0, 40, 6, 7, 7, 2012), 63);
        s2.add(new Second(0, 25, 12, 7, 7, 2012), 77);
        final TimeSeries s3 = new TimeSeries("Series 2", Second.class);
        s3.add(new Second(0, 10, 1, 7, 7, 2012), 52);
        s3.add(new Second(0, 20, 12, 7, 7, 2012), 66);
        s3.add(new Second(0, 35, 9, 7, 7, 2012), 79);
        return dataset;
     * Starting point for the demonstration application.
     * @param args  ignored.
    public static void main(final String[] args) {

        final TimeSeriesChart demo = new TimeSeriesChart("Time Series Chart");


Output :

You can also save graph as image by clicking on  "Save Graph as Image" button.

Note : In Simple Line Chart you can’t perform zooming operations. But in Time
Series Line Chart you can also perform zoom-in operations. For that, go to the 
graph area and drag mouse pointer from left-to-right and top-to-bottom in such 
a way that a rectangle or square is drawn. Drop the mouse pointer; it would 
zoom-in for that particular area (rectangle). To zoom-out drag mouse from right 
to left or bottom-to-top.

Thanks !!!!!!!!!!!! Enjoy Programming  :)


  1. how to show value when rendering on timeseries image.

  2. do you mean by values for each point plotted on chart area?

  3. its fine bt i m facing a problem in which i m reading values from csv file and in that case it is considering 12pm as 12am and ruined my graph.Please give me solution of it

  4. Hi Himanshu, as shown in function createDataset(). I think i had used almost all type of time values. Please check your code which is fetching/reading values from CSV. In Second class object you have to use 24hr format only.

  5. The setDateFormatOverride don't accept simpleDateFormat

  6. Hi shiv Modi, how to sink database display timestamp


Post a Comment

Thanks for your valuable comments.

Popular posts from this blog

Odoo/OpenERP: one2one relational field example

one2one relational field is deprecated in OpenERP version>5 but you can achieve the same using many2one relational field. You can achieve it in following two ways : 1) using many2one field in both the objects ( ) 2)  using inheritance by deligation You can easily find the first solution with little search over internet so let's start with 2nd solution. Scenario :  I want to create a one2one relation between two objects of openerp hr.employee and hr.employee.medical.details What I should do  i. Add _inherits section in hr_employee class ii. Add field medical_detail_id in hr_employee class class hr_employee(osv.osv):     _name = 'hr.employee'     _inherits = {' hr.employee.medical.details ': "medical_detail_id"}     _inherit = 'hr.employee'         _columns = {              'emp_code':fields.char('Employee Code', si

How to draw Dynamic Line or Timeseries Chart in Java using jfreechart library?

Today we are going to write a code to draw a dynamic timeseries-cum-line chart in java.   The only difference between simple and dynamic chart is that a dynamic event is used to create a new series and update the graph. In out example we are using timer which automatically calls a funtion after every 1/4 th second and graph is updated with random data. Let's try with the code : Note : I had tried my best to provide complete documentation along with code. If at any time anyone have any doubt or question please post in comments section. import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.XYPlot; import

Flickr and OAuth

What is Flickr? I think you landed on this page because you know what Flickr is, so let’s come to the point and discuss about the API. Why am explaining? Although each and everything, about API, is well documented on Flickr website here , I'm just trying to explain the whole process by dividing it into small parts. Old Authentication API The current Flickr authorization scheme is not the first one it used. In the early days of Flickr, users granted the power to an app to act on their behalf by giving  the apps their Flickr username and password. Doing so meant that in order to revoke  an app’s permission, users would have to change their Flickr password. Of course, doing that would also instantly revoke permissions of other third-­party apps with knowledge of the user’s password. The new authorization scheme is meant to correct obvious problems with the old scheme. Why should you as a user have to use your Flickr password for anything other than your dealings with Flickr?