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 | |
|---|---|
| Day | Number of Visitors |
| 1 | 10 |
| 2 | 4 |
| 3 | 6 |
| 4 | 12 |
| 5 | 11 |
| 6 | 39 |
| 7 | 33 |
| Park 2 | |
|---|---|
| Day | Number of Visitors |
| 1 | 23 |
| 2 | 15 |
| 3 | 18 |
| 4 | 5 |
| 5 | 52 |
| 6 | 66 |
| 7 | 83 |
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.
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.
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 );
}
}

0 comments:
Post a Comment