I'm using Pie-chart of JFreeChart library for my need.
And i want to display percentage with total values in pie-chart. So, i searched over google. And i found this solution which is answered by @trashgod.
Now as per answer given by him i created class which is as following :
import java.awt.Color;
import java.awt.Dimension;
import java.text.DecimalFormat;
import javax.swing.JFrame;
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;
public class TestPieChart {
private static final String KEY1 = "Datum 1";
public static final String KEY2 = "Datum 2";
public static void main(String[] args) {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue(KEY1, 45045); //49
dataset.setValue(KEY2, 53955); //151
JFreeChart someChart = ChartFactory.createPieChart(
"Header", dataset, true, true, false);
PiePlot plot = (PiePlot) someChart.getPlot();
plot.setSectionPaint(KEY1, Color.green);
plot.setSectionPaint(KEY2, Color.red);
plot.setExplodePercent(KEY1, 0.10);
plot.setSimpleLabels(true);
PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator(
"{0}: {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0%"));
plot.setLabelGenerator(gen);
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ChartPanel(someChart) {
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
});
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
What it gives output as follows:
In which percentage was 55% and 46%, Total is 101%
(Because it is taking upper limit for both values like 54.5 then 55)
But at the same time if i take value for KEY1 as 49 and KEY2 as 151, then it is giving accurate result as follows:
(Sum of both in this case is 100%)
So, My question is : Why JFreeChart is performing different for different values?
and is there any solution to fix this (total percentage will not cross 100) ?