Search code examples
javachartsjfreechart

Remove one pie section label from JFreeChart


How do I remove one label from a JFreeChart pie chart but keep the rest?

Here is a simplified version of my pie chart. I want labels for all pie slices except the "dormant" category. It's more of a placeholder.

DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Cat1", 2);
    dataset.setValue("Cat2", 4);
    dataset.setValue("Cat3", 3);
    dataset.setValue("dormant", 2);

JFreeChart chart = ChartFactory.createPieChart3D(
    null,
    dataset,
    false, // legend?
    true, // tooltips?
    false // URLs?
    );

PiePlot3D plot = (PiePlot3D) chart.getPlot();

//CREATE LABELS, but I don't want any for the "dormant" category
StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator( "{0} ({2})", new DecimalFormat("0"), new DecimalFormat("0%"));
    plot.setLabelGenerator(labelGen);

Solution

  • If the label generator returns null for the label, then the pie chart doesn't display a label for that section. So you can achieve your result like this:

        StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator(
                "{0} ({2})", new DecimalFormat("0"), new DecimalFormat("0%")) {
    
            @Override
            public String generateSectionLabel(PieDataset dataset, Comparable key) {
                if (key.equals("dormant")) {
                    return null;
                }
                return super.generateSectionLabel(dataset, key);
            }
    
        };