Creating A 3D Pie Chart In Java Using JFreeChart [Example Source Code]

JFreeChart is an open-source framework for the programming language Java, which allows the creation of complex charts in a simple way.

JFreeChart also works with GNU Classpath, a free software implementation of the standard class library for the Java programming language.

Following chart types are supported:

  • * X-Y charts (line, spline and scatter)
  • * Pie charts
  • * Gantt charts
  • * Bar charts (horizontal and vertical, stacked and independent)
  • * Single valued (thermometer, compass, speedometer)

In the following tutorial, I will show you how to create a 3D Pie Chart using JFreeChart. If you do not have the JFreeChart library and API, you can download it from their website www.jfree.org

package com.kushal.charts;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modfied On: 2009-09-23
 * 
 * Using JFreeChart to create 3D Pie Chart
 */
import java.awt.Color;
import java.io.File;
import java.io.IOException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

public class My3DPieChart {
	private static final long serialVersionUID = -8625975218180144099L;

	private PieDataset createPieDataSet() {
		DefaultPieDataset pieDataset = new DefaultPieDataset();
		/**
		 * Filling the data Visit of Sanjaal.com on a random day by Browser
		 */
		pieDataset.setValue("MS Internet Explorer", 184707);
		pieDataset.setValue("Firefox", 144556);
		pieDataset.setValue("Google Chrome", 21638);
		pieDataset.setValue("Opera", 21609);
		pieDataset.setValue("Unknown", 17916);
		pieDataset.setValue("Safari", 10850);
		pieDataset.setValue("Mozilla", 7081);
		pieDataset.setValue("Netscape", 1010);
		pieDataset.setValue("Curl", 405);
		pieDataset.setValue("LibWWW", 121);

		return pieDataset;

	}

	private JFreeChart create3DPieChart(PieDataset dataset) {

		/**
		 * createPieChart3D method Parameters: --java.lang.String title,
		 * --PieDataset dataset, --boolean legend, --boolean tooltips, --boolean
		 * urls
		 */
		JFreeChart chart = ChartFactory.createPieChart3D(
				"Sanjaal.com Visits By Browser", dataset, true, true, true);

		PiePlot3D p = (PiePlot3D) chart.getPlot();
		p.setForegroundAlpha(0.5f);
		p.setBackgroundAlpha(0.2f);

		chart.setBackgroundPaint(Color.white);
		chart.setAntiAlias(true);
		chart.setBorderVisible(true);

		return chart;

	}

	public void saveChart(JFreeChart chart, String fileLocation) {
		String fileName = fileLocation;
		try {
			/**
			 * This utility saves the JFreeChart as a JPEG First Parameter:
			 * FileName Second Parameter: Chart To Save Third Parameter: Height
			 * Of Picture Fourth Parameter: Width Of Picture
			 */
			ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Problem occurred creating chart.");
		}
	}

	public static void main(String[] args) {
		My3DPieChart chartCreator = new My3DPieChart();

		/** Create a PieDataSet* */
		PieDataset pieDataset = chartCreator.createPieDataSet();

		/** Create 3D Pie Chart based on this dataset* */
		JFreeChart chart = chartCreator.create3DPieChart(pieDataset);

		/** Define a file location to save this chart */
		String fileLocation = "C:/temp/my3DPieChart.jpg";

		/** Save the chart to the file system* */
		chartCreator.saveChart(chart, fileLocation);

		System.out.println("3D Pie Chart has been created successfully");
		System.out.println("Chart has been saved to: " + fileLocation);
	}

	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
	 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
	 * LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
	 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
	 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 * 
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */
}

The following is the output if this program:

3D Pie Chart has been created successfully
Chart has been saved to: C:/temp/my3DPieChart.jpg

Generated PieChart for the data provided looks like this:

Share

Creating 3D Pie Chart using JFreeChart with chart data read from file

Previously I wrote a tutorial on how to create a 3D Pie Chart using JFree Chart. This is just an extension to the same tutorial with some enhancement where you can read the pie chart data from a file located in your disk. You might also want to see my another tutorial on how to read a tab separated fields from a file. I use similar concept of reading the input file in this tutorial.

package com.kushal.charts;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modfied On: 2010-07-30
 *
 * Using JFreeChart to create 3D Pie Chart
 * Data will be read from a text file.
 */
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

public class My3DPieChartWithDataFromFile {
	private static final long serialVersionUID = -8625975218180144099L;

	/**
	 * @param dataFileName - Location of data file on disk
	 * @return dataset for piechart based on data read.
	 *
	 * Format of data in the file: Two columns separated by tab
	 *
	 * First Column: Data category
	 * Second Column: Data Value
	 *
	 */
	private PieDataset createPieDataSet(String dataFileName) throws IOException {
		DefaultPieDataset pieDataset = new DefaultPieDataset();

		BufferedReader bReader =new BufferedReader(new FileReader(dataFileName));
		    String s;
		    while ((s=bReader.readLine())!=null){
		      String datavalue [] = s.split("\t");
		      String category = datavalue[0];
		      String value = datavalue [1];
		      pieDataset.setValue(category, Double.parseDouble(value));
		    }
		    bReader.close();

		return pieDataset;
	}

	private JFreeChart create3DPieChart(PieDataset dataset) {

		/**
		 * createPieChart3D method Parameters: --java.lang.String title,
		 * --PieDataset dataset, --boolean legend, --boolean tooltips, --boolean
		 * urls
		 */
		JFreeChart chart = ChartFactory.createPieChart3D(
				"Sanjaal Earnings By Advertisement Agents", dataset, true, true, true);

		PiePlot3D p = (PiePlot3D) chart.getPlot();
		p.setForegroundAlpha(0.5f);
		p.setBackgroundAlpha(0.2f);

		chart.setBackgroundPaint(Color.white);
		chart.setAntiAlias(true);
		chart.setBorderVisible(false);
		chart.setTextAntiAlias(true);

		return chart;

	}

	public void saveChart(JFreeChart chart, String fileLocation) {
		String fileName = fileLocation;
		try {
			/**
			 * This utility saves the JFreeChart as a JPEG First Parameter:
			 * FileName Second Parameter: Chart To Save Third Parameter: Height
			 * Of Picture Fourth Parameter: Width Of Picture
			 */
			ChartUtilities.saveChartAsJPEG(new File(fileName), chart, 800, 600);
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Problem occurred creating chart.");
		}
	}

	public static void main(String[] args) throws Exception {
		My3DPieChartWithDataFromFile chartCreator = new My3DPieChartWithDataFromFile();

		String dataFileLocation="C:/temp/myPieChartDataFile.txt";

		/** Create a PieDataSet* */
		PieDataset pieDataset = chartCreator.createPieDataSet(dataFileLocation);

		/** Create 3D Pie Chart based on this dataset* */
		JFreeChart chart = chartCreator.create3DPieChart(pieDataset);

		/** Define a file location to save this chart */
		String fileLocation = "C:/temp/my3DPieChartFromDataFile.jpg";

		/** Save the chart to the file system* */
		chartCreator.saveChart(chart, fileLocation);

		System.out.println("3D Pie Chart has been created successfully");
		System.out.println("Chart has been saved to: " + fileLocation);
	}

	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
	 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
	 * LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
	 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
	 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 *
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */

}

You can view the input data file below.
Download the Input File for this program

The generated Pie Chart is:

Share