JFreeChart


JFreeChart is an open source Java library for creating charts. The project started in February 2000, and is currently the most widely used Java charting library. It offers a large number of charts, examples of which can be found here.

To get started with JFreeChart in your maven project, add the following to your pom.xml

<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.17</version>
</dependency>

First, you need to create a Dataset to display in your chart. One of the most used Datasets by the library is the CategoryDataset, so let’s focus on that one.

DefaultCategoryDataset set = new DefaultCategoryDataset();
for (int i = 0; i < records.size(); i++){
Record record = records.get(i);
set.addValue(record.getCorrect(), // y-value
record.getStage(), // dataset
Integer.valueOf(i)); // x-value
}

The parameters for the addValue method are as follows:

  1. The actual value of this record
  2. The row key. When adding multiple sets to the same chart, so you can compare them, use different values for this parameter
  3. The column key, or the column at which this value will appear. Since this must implement the Comparable interface, it will be sorted.

Once you have the dataset, you can use it to create  the chart itself.

JFreeChart chart = ChartFactory
.createLineChart("Score progress over time", // title
"Iteration", // category axis label
"Score", // value axis label
set); // dataset

With this dataset, you can create a number of charts. In this case, a line chart will be created, but you can also create an area chart, a bar chart, a stacked area / bar chart, and a 3D line / bar chart.

The library provides components to display the chart on screen, and to write it to file. The latter option involves only a couple of lines of code.

File output = new File(WORK_DIR, "chart.png");
try {
ChartUtilities.saveChartAsJPEG(output, // file
chart, // chart
800, // width
600); // height
} catch (IOException e) {
e.printStackTrace();
}

And when everything is ok, you’ll end up with something like this:chart


Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *