Sunday, 7 June 2015

JFreeChart Setting labels for Piechart sections

You can set custom labels for sections of a piechart. By default, pie chart has, section name as label, if you want custom label you can do it by using “setLabelGenerator” method of PiePlot.

plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})"));

Generator use Java’s MessageFormat class to construct labels.  {0}, {1} in the above example has special meaning.


Key
Descriptions
{0}
Take Section key as a string
{1}
Take section value
{2}
Take section value as a percentage of all values in the data set.

import java.awt.Color;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

public class Main {
 public static void main(String args[]) {
  /* Create dataset */
  DefaultPieDataset dataset = new DefaultPieDataset();
  dataset.setValue("2004-2005", 58);
  dataset.setValue("2005-2006", 41);
  dataset.setValue("2006-2007", 85.3);
  dataset.setValue("2007-2008", 81);

  /* create chart */
  JFreeChart chart = ChartFactory.createPieChart("Simple Piechart",
    dataset);

  /* Get PiePlot object */
  PiePlot plot = (PiePlot) chart.getPlot();

  /* Set colors to sections */
  plot.setSectionPaint("2004-2005", new Color(255, 0, 0));
  plot.setSectionPaint("2005-2006", new Color(0, 255, 0));
  plot.setSectionPaint("2006-2007", new Color(0, 0, 255));
  plot.setSectionPaint("2007-2008", new Color(0, 0, 0));
  
  /* Disable outlines */
  plot.setOutlineVisible(true);

  /* Set custom labels */
  plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})"));
  
  /* create and display chart on frame */
  ChartFrame frame = new ChartFrame("JFreeChart Demo", chart);
  frame.pack();
  frame.setVisible(true);
 }
}


Output




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment