This tutorial shows you how to draw XY line charts using JFreechart - the most popular chart generation framework in Java. An XY line chart is suitable for representing dataset in form of series of (x, y) points, such as mathematical graphs, coordinate-based objects, etc. Finally, you will able to create a chart looks like the following:

XY line chart demo

NOTE: To use JFreechart in your project, add the following JAR files to the project’s classpath:

  • jcommon-VERSION.jar
  • jfreechart-VERSION.jar

 

1. A Java Swing program for XY line chart example

Here is the skeleton of a Swing program that demonstrates how to draw an XY line chart:

/**
 * This program demonstrates how to draw XY line chart with XYDataset
 * using JFreechart library.
 * @author www.codejava.net
 *
 */
public class XYLineChartExample extends JFrame {

	public XYLineChartExample() {
		super("XY Line Chart Example with JFreechart");

		JPanel chartPanel = createChartPanel();
		add(chartPanel, BorderLayout.CENTER);

		setSize(640, 480);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
	}

	private JPanel createChartPanel() {
		// creates a line chart object
		// returns the chart panel
	}

	private XYDataset createDataset() {
		// creates an XY dataset...
		// returns the dataset
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new XYLineChartExample().setVisible(true);
			}
		});
	}
}

This program displays a window that contains a chart panel generated by JFreechart. Now, we are going to see the detailed implementations of the createChartPanel() and createDataset() methods.

 

2. Creating an XY dataset

Write code for the createDataset() method as follows:

private XYDataset createDataset() {
	XYSeriesCollection dataset = new XYSeriesCollection();
	XYSeries series1 = new XYSeries("Object 1");
	XYSeries series2 = new XYSeries("Object 2");
	XYSeries series3 = new XYSeries("Object 3");

	series1.add(1.0, 2.0);
	series1.add(2.0, 3.0);
	series1.add(3.0, 2.5);
	series1.add(3.5, 2.8);
	series1.add(4.2, 6.0);

	series2.add(2.0, 1.0);
	series2.add(2.5, 2.4);
	series2.add(3.2, 1.2);
	series2.add(3.9, 2.8);
	series2.add(4.6, 3.0);

	series3.add(1.2, 4.0);
	series3.add(2.5, 4.4);
	series3.add(3.8, 4.2);
	series3.add(4.3, 3.8);
	series3.add(4.5, 4.0);

	dataset.addSeries(series1);
	dataset.addSeries(series2);
	dataset.addSeries(series3);

	return dataset;
}

This creates some dummy data for an XYDataset which is required by the ChartFactory.createXYLineChart() method. The XYSeriesCollection class is an XYDataset’s implementation which holds a collection of XYSeries. The usage is pretty straightforward. Here are the steps to add (x, y) data for a series:

XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Series Name");

series1.add(x1, y1);
series1.add(x2, y2);
// ...
series1.add(xN, yN);

dataset.addSeries(series1);

Note that, by default, the XYSeries class will sort the added items into ascending order by x-values, and duplicate x-values are permitted. If you want to change the defaults, use the appropriate constructors as follows:

boolean autoSort = false;
XYSeries series = new XYSeries("Object 1", autoSort);

Or:

boolean autoSort = false;
boolean allowDuplicateXValues = false;
XYSeries series = new XYSeries("Object 1", autoSort, allowDuplicateXValues);

In reality, the data can be loaded from database, text files, CSV files, Excel files, etc.

 

3. Creating an XY line chart

Write code for the createChartPanel() method as follows:

private JPanel createChartPanel() {
	String chartTitle = "Objects Movement Chart";
	String xAxisLabel = "X";
	String yAxisLabel = "Y";

	XYDataset dataset = createDataset();

	JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, 
			xAxisLabel, yAxisLabel, dataset);

	return new ChartPanel(chart);
}

The ChartFactory class provides two methods for creating an XY line chart as follows:

  • createXYLineChart(title, categoryAxisLabel, valueAxisLabel, dataset)
  • createXYLineChart(title, categoryAxisLabel, valueAxisLabel, dataset, orientation, legend, tooltips, urls)

The following screenshot is taken when running the above Swing program that creates the line chart using the first method:

XY line chart demo 1

The second variant of the createXYLineChart() method allows us to specify the plot orientation, show/hide the legend box… Here’s an example:

boolean showLegend = false;
boolean createURL = false;
boolean createTooltip = false;

JFreeChart chart = ChartFactory.createXYLineChart(chartTitle,
		xAxisLabel, yAxisLabel, dataset,
		PlotOrientation.HORIZONTAL, showLegend, createTooltip, createURL);

Here’s the result (the orientation is reversed and there is no legend):

XY line chart demo 2

 

4. Some customizations for XY line chart

Here are some examples of chart customization provided for your references, in case the default look and feel doesn’t suite your needs.

Basically, we get a reference of the plot from the chart to do the customizations on the plot instance:

XYPlot plot = chart.getXYPlot();

Setting custom renderer for the series lines:

XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
plot.setRenderer(renderer);

Output:

XY line chart customization 1

 

Setting custom paint color and stroke for each series line:

XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

// sets paint color for each series
renderer.setSeriesPaint(0, Color.RED);
renderer.setSeriesPaint(1, Color.GREEN);
renderer.setSeriesPaint(2, Color.YELLOW);

// sets thickness for series (using strokes)
renderer.setSeriesStroke(0, new BasicStroke(4.0f));
renderer.setSeriesStroke(1, new BasicStroke(3.0f));
renderer.setSeriesStroke(2, new BasicStroke(2.0f));

plot.setRenderer(renderer);

Output:

XY line chart customization 2

Setting custom paint color and stroke for the plot’s outlines (chart borders):

plot.setOutlinePaint(Color.BLUE);
plot.setOutlineStroke(new BasicStroke(2.0f));

Setting background color for the plot:

plot.setBackgroundPaint(Color.DARK_GRAY);

Setting visibility and paint color for the grid lines:

plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.BLACK);

plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.BLACK);

And here is the result of all the customizations above:

XY line chart demo

 

5. Saving the chart as an image

The ChartUtilities class provides some methods which we can use to export the chart graphics to an image file. For example, the following code snippet saves the chart to a PNG image file:

File imageFile = new File("XYLineChart.png");
int width = 640;
int height = 480;

try {
	ChartUtilities.saveChartAsPNG(imageFile, chart, width, height);
} catch (IOException ex) {
	System.err.println(ex);
}

To save as JPEG image, use the saveChartAsJPEG() method.

 

API References:

 

Other Java Graphics Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (XYLineChartExample.java)XYLineChartExample.java[Java source file]4 kB

Add comment

   


Comments 

#17kuldeep2020-05-21 00:54
can we show data point values in xy line plot?
Quote
#16JoshiKiran2017-09-08 15:30
www.codejava.net"is the greatest website! thank tou so much!
Quoting JoshiKiran:
this is awesome! thank you so much!

www.codejava.net"is the greatest website! thank tou so much!
Quote
#15JoshiKiran2017-09-08 15:24
this is awesome! thank you so much!
Quote
#14Joshi2017-02-20 02:23
Hi,

can you please tell me how can we remove the extra line along the x and y axis, its not the border but a line along the x and y axis.

Thank you
Quote
#13Kiran2016-09-27 02:26
Its working.Thank you so much!!
Quote