Chart a new course with JFreeChart

Add charts to your Java applications

As a developer, I am often asked to demonstrate new applications. After doing many demos, I noticed that users are often initially more interested in what an application looks like than what it does. I have also noticed that one of the best ways to make a good first impression is with a colorful, three-dimensional chart.

JFreeChart is a popular open source Java charting library that can generate most common chart types, including pie, bar, line, and Gantt charts. In addition, the JFreeChart API supports many interactive features, such as tool tips and zooming. JFreeChart provides an excellent choice for developers who need to add charts to Swing- or Web-based applications.

Note: The following examples are based on JFreeChart version 0.9.4. To compile and run the code included with this column, you must have two jar files from the JFreeChart distribution, jfreechart-0.9.4.jar and jcommon-0.7.1.jar, in your classpath.

Charts and datasets

To create a chart using JFreeChart, you must create a Dataset, which you then use to create a JFreeChart. A Dataset contains the data that displays in the chart. JFreeChart features many different Dataset objects, which you can use to create assorted types of charts. Once you create a Dataset, you next create the actual chart. JFreeChart uses an object appropriately named JFreeChart to represent charts. You create JFreeChart objects from Dataset objects with the ChartFactory class. In the following examples, we will create pie, XY, and bar charts along with their corresponding Dataset objects.

Pie chart

A pie chart is created from a PieDataset. The following example creates a PieDataset using the DefaultPieDataset class, adds two values via the setValue() method, and then creates a pie chart with the ChartFactory's createPieChart() method. This example will create a pie chart with the title "Sample Pie Chart," a legend, and two slices: JavaWorld with 75 percent of the pie, and Other with the other 25 percent:

DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("JavaWorld", new Integer(75));
pieDataset.setValue("Other", new Integer(25));
JFreeChart chart = ChartFactory.createPieChart
                     ("Sample Pie Chart",   // Title
                      pieDataset,           // Dataset
                      true                  // Show legend  
                     );

XY chart

An XYDataset can create area, line, and step XY charts. The following example creates an XYDataset from a series of data containing three XY points. Next, ChartFactory's createAreaXYChart() method creates an area XY chart. In addition to parameters for title, dataset, and legend, createAreaXYChart() takes in the labels for the X and Y axes:

XYSeries series = new XYSeries("Average Size");
series.add(20.0, 10.0);
series.add(40.0, 20.0);
series.add(70.0, 50.0);
XYDataset xyDataset = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createAreaXYChart
                     ("Sample XY Chart",  // Title
                      "Height",           // X-Axis label
                      "Weight",           // Y-Axis label
                      xyDataset,          // Dataset
                      true                // Show legend
                     );

Bar chart

A CategoryDataset can create numerous different charts, including horizontal and vertical bar charts. The following example creates a CatagoryDataset with two series of data and two categories, and then creates a 3D vertical bar chart from this dataset. This example creates a chart that compares the sales growth in two quarters over two years:

String[] seriesNames = new String[] {"2001", "2002"};
String[] categoryNames = new String[] {"First Quater",
                                       "Second Quater"};
Number[][] categoryData = new Integer[][] {{new Integer(20),
                                            new Integer(35)},
                                           {new Integer(40),
                                            new Integer(60)}
                                           };
CategoryDataset categoryDataset = new DefaultCategoryDataset
                                        (seriesNames,
                                         categoryNames,
                                         categoryData);
JFreeChart chart = ChartFactory.createVerticalBarChart3D
                     ("Sample Category Chart", // Title
                      "Quarters",              // X-Axis label
                      "Sales",                 // Y-Axis label
                      categoryDataset,         // Dataset
                      true                     // Show legend
                     );

Integrate JFreeChart

Integrating JFreeChart into a Swing application is relatively easy. Just create a BufferedImage from the chart and use the image as an icon for a JLabel:

BufferedImage image = chart.createBufferedImage(500,300);
JLabel lblChart = new JLabel();
lblChart.setIcon(new ImageIcon(image));

JFreeChart also includes a class named ChartUtilities that provides several methods for saving charts to files or writing them out to streams in JPEG or PNG format. For example, the following piece of code can export a chart to a JPEG:

ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart, 500, 300);

The methods in the ChartUtilities class can be used to create JPEGs for use in a static Webpage, or used in a JSP (JavaServer Pages)/servlet-based application to dynamically stream charts to Webpages.

On your mark, get set, chart!

This article showed you how to create some common datasets and charts with the JFreeChart library. JFreeChart has much more to offer, including many chart types and advanced features such as combined charts and chart mouse events. Visit the JFreeChart homepage for the software's latest version, a servlet-based demo, links to projects using JFreeChart, and more.

Erik Swenson is a consultant and the founder of Open Source Software Solutions. Swenson specializes in Java development using open source software and components. Moreover, he developed JasperEdit and OpenReports open source projects.

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more