JFreeChart - Pie Chart example

Posted on January 8, 2017


A pie chart is a circular graph which is divided into sectors in which the area of each sector represents the size of the data.

In this post, we will show you how to create a pie chart using the JFreeChart java library.

JAR dependencies

Add the following jars to build path of your project, if you are using Eclipse.

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

Or add the following dependency to pom.xml file, if you are using Maven.

<dependencies>
  <dependency>
     <groupId>org.jfree</groupId>
     <artifactId>jfreechart</artifactId>     
     <version>1.0.19</version>
  </dependency>
</dependencies>

Sample data for Pie chart

The following table represents the marks distribution for a class.

Marks RangeNumber of Students
80-100120
60-7980
40-5920
20-397
0-193

Pie Chart example

The following example create a pie chart from the above sample data.

PieChartExample.java

package com.boraji.tutorial.jfreechart.piechart;

import java.text.DecimalFormat;

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.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
/**
 * @author imssbora
 */
public class PieChartExample extends JFrame {
  private static final long serialVersionUID = 6294689542092367723L;

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

    // Create dataset
    PieDataset dataset = createDataset();

    // Create chart
    JFreeChart chart = ChartFactory.createPieChart(
        "Pie Chart Example",
        dataset,
        true, 
        true,
        false);

    //Format Label
    PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator(
        "Marks {0} : ({2})", new DecimalFormat("0"), new DecimalFormat("0%"));
    ((PiePlot) chart.getPlot()).setLabelGenerator(labelGenerator);
    
    // Create Panel
    ChartPanel panel = new ChartPanel(chart);
    setContentPane(panel);
  }

  private PieDataset createDataset() {

    DefaultPieDataset dataset=new DefaultPieDataset();
    dataset.setValue("80-100", 120);
    dataset.setValue("60-79", 80);
    dataset.setValue("40-59", 20);
    dataset.setValue("20-39", 7);
    dataset.setValue("0-19", 3);
    return dataset;
  }

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

Outputpiechart.png