Wednesday, December 17, 2008

Generate Charts and Graphs in Java Using JFreeChart

I was recently looking for an open source charting and graphing API for Java when I came across JFreeChart. They describe JFreeChart as a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications.

One of the first things I noticed was that there is very little to no documentation on how to use JFreeChart and I am assuming that is because they sell their Developer's Guide to support the project. While that is definitely a good way to support their project, it makes it hard for people to test out the API. So, hopefully, I can help you get started with using JFreeChart. I strongly encourage purchasing the Developer's Guide if you plan on using JFreeChart in your projects.

A Simple Line Chart
We'll take a look at a simple dataset that would be used in a basic line graph using JFreeChart. Our datasets will represent the number of visitors counted at local parks over a 7 day period.


Park 1
DayNumber of Visitors
110
24
36
412
511
639
733
Park 2
DayNumber of Visitors
123
215
318
45
552
666
783

We are going to create a graph using the dataset above with the JFreeChart API. The sample class below will show how to generate a line graph using the data above.


package org.javaconfessions.sample;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.ChartUtilities;

import java.io.File;
import java.io.FileOutputStream;

class XYChartSample {

public void buildChart() throws Exception {

XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries xySeries = new XYSeries( "Park 1" );
xySeries.add( 1, 10 );
xySeries.add( 2, 4 );
xySeries.add( 3, 6 );
xySeries.add( 4, 12 );
xySeries.add( 5, 11 );
xySeries.add( 6, 29 );
xySeries.add( 7, 33 );

XYSeries xySeries2 = new XYSeries( "Park 2" );
xySeries2.add( 1, 23 );
xySeries2.add( 2, 15 );
xySeries2.add( 3, 18 );
xySeries2.add( 4, 5 );
xySeries2.add( 5, 52 );
xySeries2.add( 6, 66 );
xySeries2.add( 7, 83 );

dataset.addSeries( xySeries );
dataset.addSeries( xySeries2 );

JFreeChart chart = ChartFactory.createXYLineChart( "Park Chart",
"Day",
"# of Visitors",
dataset,
PlotOrientation.VERTICAL,
true,
false,
false );

FileOutputStream out = new FileOutputStream( new File( "parkchart.png" ) );
ChartUtilities.writeChartAsPNG( out, chart, 400, 200 );

}

}
This is just a basic example of how you can generate charts using JFreeChart. You can see at the end I also show an example of another useful feature found in JFreeChart, the capability to write out charts as images. In this example, I wrote out the chart as a PNG file. Here is an example of how that chart would look if you ran the code above.

0 comments:

© 2010 Confessions of a Java Programmer, All Rights Reserved