Question

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);
Was it helpful?

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);
        }

    };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top