JFreeChart - Area Chart example

Posted on January 20, 2017


An area chart is a line chart with the areas below the lines filled with colors. In this post, we will show you how to create an area chart using the the JFreeChart java library.

JAR dependencies

Add the following jars to build path of your project.

  • jfreechart-1.0.19.jar
  • jcommon-1.0.23.jar

Sample data for Area chart

The following table represents the smartphone OS market share in India.

Mobile OSYearShare (%)
Android200510
Android201020
Android201530
iOS20057
iOS201011
iOS201516
Window Mobile20055
Window Mobile20109
Window Mobile201514

Java program for Area chart

The following example create an area chart from the above sample data.

AreaChartExample.java

package com.boraji.tutorial.jfreechart.areachart;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 * @author imssbora
 */
public class AreaChartExample extends JFrame {

  private static final long serialVersionUID = 1L;

  public AreaChartExample(String title) {
    super(title);

    // Create dataset
    DefaultCategoryDataset dataset = createDataset();

    // Create chart
    JFreeChart chart = ChartFactory.createAreaChart(
        "Smartphone Platform Market Share",
        "Year", 
        "Percentage(%)",
        dataset);

    // Create Panel
    ChartPanel panel = new ChartPanel(chart);
    setContentPane(panel);
  }

  private DefaultCategoryDataset createDataset() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    dataset.addValue(10, "Android", "2005");
    dataset.addValue(20, "Android", "2010");
    dataset.addValue(30, "Android", "2015");

    dataset.addValue(7, "iOS", "2005");
    dataset.addValue(11, "iOS", "2010");
    dataset.addValue(16, "iOS", "2015");

    dataset.addValue(5, "Window Mobile", "2005");
    dataset.addValue(9, "Window Mobile", "2010");
    dataset.addValue(14, "Window Mobile", "2015");

    return dataset;
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      AreaChartExample example = new AreaChartExample("Area Chart Example | BORAJI.COM");
      example.setSize(800, 400);
      example.setLocationRelativeTo(null);
      example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      example.setVisible(true);
    });
  }
}

Output

 areachart.png