I got 78 labels in a pie chart like this picture.
And I want to show only top 3 labels in descending order.
How can I do this?
Create a custom PieSectionLabelGenerator
and return null
when you do not like to display the label.
Example
public class PieMaximumLabelsGenerator extends StandardPieSectionLabelGenerator {
private static final long serialVersionUID = 1385777973353453096L;
private int nrLabels;
private boolean showFirst;
/**
* A custom label generator to show only limited numbers of labels
* @param nrLabels, number of labels to show
* @param showFirst, if true, show first labels otherwise show the last
*/
public PieMaximumLabelsGenerator(int nrLabels, boolean showFirst){
this.nrLabels = nrLabels;
this.showFirst = showFirst;
}
@Override
public String generateSectionLabel(PieDataset dataset, Comparable key) {
int index = dataset.getIndex(key);
if (showFirst){
if (index>=nrLabels){
return null; //no more lables if index is above
}
}else{
if (index<dataset.getItemCount()-nrLabels){
return null; //no labels if index is not enough
}
}
return super.generateSectionLabel(dataset, key);
}
}
Then set this to your plot
((PiePlot) chart.getPlot()).setLabelGenerator(new PieMaximumLabelsGenerator(3, false));
Output, similar example but displaying first 5 values instead of last 3, hence ((PiePlot) chart.getPlot()).setLabelGenerator(new PieMaximumLabelsGenerator(5, true));
My preference however is to display label if the arc angle of slice is large enough. This can be done by collecting totale values of items in the chart and then calculating the angle using Number value = dataset.getValue(key);
in generateSectionLabel
to get the current angle (dimension) of slice.