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: Qweb Templates Cache Issue

Hi Everyone, Today I was working on a hotel booking template in Odoo and changes made in the Qweb template(.xml) were not reflecting on updating module with odoo service restart. Tried few times without any success :(. Finally, I decided to delete the old template from Odoo backend and then update module again and it worked like a charm!! :) Steps to delete template from backend: Settings --> User Interface --> Views --> Search by template name Delete the used template. Although it's a small post, but I'm sure it will meet the purpose and help someone in the future. Thanks!!! Enjoy Programming!! :) Reference Links: ===================================

Odoo12/13: Add an extra action in the tree view action button

This post will help you to add an action window in Odoo. Odoo13: <act_window id="action_make_bank_payment"              name="Do Bank Payment"              res_model="account.ob.payment"              binding_model="account.move"              view_mode="form"              target="new"              binding_views="list,form"              domain="[('type','=', 'in_invoice')]"              groups="account.group_account_user" /> Odoo12: <act_window id="action_make_bank_payment"              name="Do Bank Payment"              res_model="account.ob.payment"             view_mode="tree,form"              domain="[('type','=', 'in_invoice')]"              groups="account.group_account_user" /> Thanks!!! Enjoy Programming!! :) Reference:

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