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

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

Odoo: Download Binary File in v10

To download any binary file in Odoo10 following is the link: http://127.0.0.1:8069/web/content?model=<module_name>&field=<field_name>&filename_field=<field_filename>&id=<object_id> module_name    - the name of the model with the Binary field field_name         - the name of the Binary field object_id            - id of the record containing particular file. field_filename    - name of a Char field containing file's name (optional). So if you want to call a function on button click and download the file, code is as follow: file_url = "http://127.0.0.1:8069/web/content?model=<module_name>&field=<field_name>&filename_field=<field_filename>&id=<object_id>" return {     'type': 'ir.actions.act_url',     'url': file_url,     'target': 'new' } In Reports or web page, you can use it as: <t t-foreach="files&qu