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...

TimeSeriesChart.java

//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.io.File;
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.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
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) {

        super(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) {
                try{                                       
                    //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.addExtension("jpg");
                    filter.setDescription("JPEG image");
                    chooser.setFileFilter(filter);
                    int choice = 0;
                    do{
                        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);
                }
            }
        });
       
        customPanel.add(saveButton);
         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",
            "Date",
            "Value",
            dataset,
            true,
            true,
            false
        );

        chart.setBackgroundPaint(Color.LIGHT_GRAY);//light gray
       
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(new Color(0xffffe0));
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.lightGray);
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(false);
               
        final XYItemRenderer xyitemrenderer  = plot.getRenderer();
        if (xyitemrenderer  instanceof XYLineAndShapeRenderer) {
            final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyitemrenderer;
            renderer.setBaseShapesFilled(true);
            renderer.setBaseShapesVisible(true);
            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);
            renderer.setBaseOutlineStroke(stroke);
                       
        }
       
               
        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
        xaxis.setVerticalTickLabels(true);
       
        //Try to play with it. It will work only in case of  horizontal tick mark
        xaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
       
        //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
        yaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
       
        return chart;

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

        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.setDomainIsPointsInTime(true);
                
        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);
       
        dataset.addSeries(s1);
        dataset.addSeries(s2);
        dataset.addSeries(s3);
       
        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");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);
   }

}


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  :)



Comments

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

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

    ReplyDelete
  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

    ReplyDelete
  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.

    ReplyDelete
  5. The setDateFormatOverride don't accept simpleDateFormat

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

    ReplyDelete

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: =================================== https://www.odoo.com/forum/help-1/question/odoo-cache-and-updating-qweb-templates-84492

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: https://www.odoo.com/es_

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 ( http://tutorialopenerp.wordpress.com/2014/04/23/one2one/ ) 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