JFreeChart - XY Line Chart example

Posted on January 1, 2017


A XY line chart (Scatter Plot) has points that show the relationship between two sets of data and these data sets are presented by (x,y) coordinates.

In this post we will show you how to create a XY line chart using the JFreeChart java library.

JAR dependencies

Add the following jars to build path of your project, if you are using Eclipse.

  • jfreechart-1.0.19.jar
  • jcommon-1.0.23.jar

Or add the following dependency to pom.xml file, if you are using Maven.

<dependencies>
  <dependency>
     <groupId>org.jfree</groupId>
     <artifactId>jfreechart</artifactId>     
     <version>1.0.19</version>
  </dependency>
</dependencies>

Sample data for XY Line chart 

Below is the sample data for XY line chart.

XY = X + 2
24
810
1012
1315
1719
1820
2023

XY Line Chart example

The following example creates a XY Line chart from the above data sets.

XYLineChartExample.java

package com.boraji.tutorial.jfreechart.xychart;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
 * @author imssbora
 */
public class XYLineChartExample extends JFrame {
  private static final long serialVersionUID = 6294689542092367723L;

  public XYLineChartExample(String title) {
    super(title);

    // Create dataset
    XYDataset dataset = createDataset();

    // Create chart
    JFreeChart chart = ChartFactory.createXYLineChart(
        "XY Line Chart Example",
        "X-Axis",
        "Y-Axis",
        dataset,
        PlotOrientation.VERTICAL,
        true, true, false);

    // Create Panel
    ChartPanel panel = new ChartPanel(chart);
    setContentPane(panel);
  }

  private XYDataset createDataset() {
    XYSeriesCollection dataset = new XYSeriesCollection();

    XYSeries series = new XYSeries("Y = X + 2");
    series.add(2, 4);
    series.add(8, 10);
    series.add(10, 12);
    series.add(13, 15);
    series.add(17, 19);
    series.add(18, 20);
    series.add(21, 23);

    //Add series to dataset
    dataset.addSeries(series);
    
    return dataset;
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      XYLineChartExample example = new XYLineChartExample("XY Chart Example | BORAJI.COM");
      example.setSize(800, 400);
      example.setLocationRelativeTo(null);
      example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      example.setVisible(true);
    });
  }
}

Output

xylinechart.png