Using JFreechart to draw line chart with CategoryDataset
- Details
- Written by Nam Ha Minh
- Last Updated on 10 August 2019   |   Print Email
JFreechart has been the leading library for drawing variety of charts in Java for years. This chart generation framework can be used to draw almost kinds of charts with high quality, flexibility and great level of customizations. In this tutorial, we show you how to use JFreechart to draw line chart - one of the most commonly used chart types. In addition, some basic customizations are provided for your convenience. We will have the following chart finally:
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 line chart example
The following Java class creates a simple Swing program that displays a JFrame window which contains a chart panel:
/** * This program demonstrates how to draw line chart with CategoryDataset * using JFreechart library. * @author www.codejava.net * */ public class LineChartWithCategoryDatasetExample extends JFrame { public LineChartWithCategoryDatasetExample() { super("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 CategoryDataset createDataset() { // creates chart dataset... // returns the dataset } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new LineChartWithCategoryDatasetExample().setVisible(true); } }); } }
This is just a skeleton, as you can see the createChartPanel() and createDataset() methods don’t have any implementations.
2. Creating a dataset
Write code for the createDataset() method as follows:
private CategoryDataset createDataset() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); String series1 = "Java"; String series2 = "PHP"; String series3 = "C++"; String series4 = "C#"; dataset.addValue(5.0, series1, "2005"); dataset.addValue(4.8, series1, "2006"); dataset.addValue(4.5, series1, "2007"); dataset.addValue(4.3, series1, "2008"); dataset.addValue(4.0, series1, "2009"); dataset.addValue(4.1, series1, "2010"); dataset.addValue(4.2, series1, "2011"); dataset.addValue(4.2, series1, "2012"); dataset.addValue(4.0, series1, "2013"); dataset.addValue(4.0, series2, "2005"); dataset.addValue(4.2, series2, "2006"); dataset.addValue(3.8, series2, "2007"); dataset.addValue(3.6, series2, "2008"); dataset.addValue(3.4, series2, "2009"); dataset.addValue(3.4, series2, "2010"); dataset.addValue(3.3, series2, "2011"); dataset.addValue(3.1, series2, "2012"); dataset.addValue(3.2, series2, "2013"); dataset.addValue(3.6, series3, "2005"); dataset.addValue(3.4, series3, "2006"); dataset.addValue(3.5, series3, "2007"); dataset.addValue(3.2, series3, "2008"); dataset.addValue(3.2, series3, "2009"); dataset.addValue(3.0, series3, "2010"); dataset.addValue(2.8, series3, "2011"); dataset.addValue(2.8, series3, "2012"); dataset.addValue(2.6, series3, "2013"); dataset.addValue(3.2, series4, "2005"); dataset.addValue(3.2, series4, "2006"); dataset.addValue(3.0, series4, "2007"); dataset.addValue(3.0, series4, "2008"); dataset.addValue(2.8, series4, "2009"); dataset.addValue(2.7, series4, "2010"); dataset.addValue(2.6, series4, "2011"); dataset.addValue(2.6, series4, "2012"); dataset.addValue(2.4, series4, "2013"); return dataset; }
This creates some dummy data for a DefaultCategoryDataset which is required by the ChartFactory.createLineChart() method. The data is added to the dataset in the following form:
dataset.addValue(value, seriesName, categoryName);
Each series has values are associates with categories. As shown in the above code, we create four series (namely Java, PHP, C++ and C#). The categories are times (2005, 2006 …) and the values are popularity degrees (5.0, 4.6, 3.2 …).
In reality, the data can be loaded from database, text files, CSV files, Excel files, etc.
3. Creating a line chart
Write code for the createChartPanel() method as follows:
private JPanel createChartPanel() { String chartTitle = "Programming Languages Trends"; String categoryAxisLabel = "Interest over time"; String valueAxisLabel = "Popularity"; CategoryDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createLineChart(chartTitle, categoryAxisLabel, valueAxisLabel, dataset); return new ChartPanel(chart); }
The ChartFactory class provides various methods to create many kinds of chart, and there are four methods for creating a line chart:
- createLineChart(title, categoryAxisLabel, valueAxisLabel, dataset)
- createLineChart(title, categoryAxisLabel, valueAxisLabel, dataset, orientation, legend, tooltips, urls)
- createLineChart3D(title, categoryAxisLabel, valueAxisLabel, dataset)
- createLineChart3D(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:
The second variant of the createLineChart() 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.createLineChart(chartTitle, categoryAxisLabel, valueAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, createTooltip, createURL);
Here’s the result (the orientation is reversed and there is no legend):
The createLineChart3D() methods allow us to draw a 3D line chart. For example:
JFreeChart chart = ChartFactory.createLineChart3D(chartTitle, categoryAxisLabel, valueAxisLabel, dataset);
And the following screenshot is the result:
4. Some customizations for line chart
Often times, the chart’s default look and feel doesn’t suite one’s needs. So here are some customization examples provided for your references.
Basically, we get a reference of the plot from the chart to do the customizations on the plot instance:
CategoryPlot plot = chart.getCategoryPlot();
Setting custom renderer for the series lines:
LineAndShapeRenderer renderer = new LineAndShapeRenderer(); plot.setRenderer(renderer);
Output:
Setting custom paint color and stroke for each series line:
LineAndShapeRenderer renderer = new LineAndShapeRenderer(); // sets paint color for each series renderer.setSeriesPaint(0, Color.RED); renderer.setSeriesPaint(1, Color.GREEN); renderer.setSeriesPaint(2, Color.BLUE); renderer.setSeriesPaint(3, 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)); renderer.setSeriesStroke(3, new BasicStroke(1.5f)); plot.setRenderer(renderer);
Output:
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.CYAN);
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:
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("LineChart.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:
- How to add watermark for images using Java
- How to resize images using Java
- How to convert image format using Java
- How to draw image with automatic scaling in Java
- How to capture screenshot programmatically in Java
- How to draw text vertically with Java Graphics2D
- How to Create Zoomable User Interface Java Programs with Piccolo2D Framework
- Drawing lines examples with Java Graphics2D
- Drawing Rectangles Examples with Java Graphics2D
- Using JFreechart to draw XY line chart with XYDataset
Comments
I'm sorry my English is so bad.
Yes, such tutorial will be coming soon. Thanks for asking.