Is there a way to include some arbitrary text in the legend in a JFreeChart PieChart? I know it's possible to assign a PieSectionLabelGenerator
in order to customize the labels of each of the Pie's sections that appear on the chart's legend.
I'd like to insert some text into the legend, completely unrelated to any of the pie sections, like, for instance, "Legend".
I'm building the Chart like this:
private JFreeChart constructChart() {
List<Object[]> llistaValorsArr;
ParamsDTO dto = (ParamsDTO) getModelObject();
List llistaValors = statisticsService.getStatistics(dto);
if (!llistaValors.isEmpty() && !(llistaValors.get(0) instanceof Object[])){
llistaValorsArr = new ArrayList<Object[]>();
llistaValorsArr.add(new Object[]{llistaValors.get(0), ""});
}
else{
llistaValorsArr = (List<Object[]>) llistaValors;
}
DefaultPieDataset dataSet = new DefaultPieDataset();
for (Object[] objects : llistaValorsArr) {
dataSet.setValue((Comparable) objects[1], (Number)objects[0]);
}
String title = "Total: " + new Double(DatasetUtilities.calculatePieDatasetTotal(dataSet)).intValue();
JFreeChart chart = ChartFactory.createPieChart(title, dataSet, true, false, true);
final PiePlot plot = (PiePlot) chart.getPlot();
plot.setForegroundAlpha(0.5f);
plot.setNoDataMessage("No data");
PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator("{0} - {1} ({2})"){
@Override
protected Object[] createItemArray(PieDataset dataset, Comparable key) {
// TODO Auto-generated method stub
Object[] array = super.createItemArray(dataset, key);
array[0] = getEntityLabel(key);
return array;
}
};
plot.setLabelGenerator(labelGenerator);
plot.setLegendLabelGenerator(labelGenerator);
//plot.setStartAngle(290);
boolean circular = true;
plot.setCircular(circular);
return chart;
}
UPDATE: I just found out JFreeChart.addSubtitle()
, hoping it would allow to position it just above the legend, but it will just add a subtitle next to the chart's Title.
UPDATE 2: I've been trying to place a TextTitle
inside the LegendTitle
's wrapper, but it appears to be null at chart construction time.
LegendTitle legend = chart.getLegend();
BlockContainer container = legend.getWrapper();
container.add(new TextTitle("Legend"));
It shouldn't really be that complicated to add a 'Legend' text to decorate the legend.
Looking at the source code of org.jfree.chart.JFreeChart
, and seeing that addLegend()
is nothing more than addSubtitle()
behind the scenes, everything indicates that this should be achieved using addSubtitle()
.
Looking at the part where org.jfree.chart.JFreeChart
adds its own LegendTitle
item, we can find the setup JFreeChart
uses for placing the Legend here.
So, the solution is to add, for instance, a TextTitle
to the Chart
in an analogous way. The relevant setting here is setPosition(RECTANGLE.BOTTOM)
.
TextTitle legendText = new TextTitle("This is LEGEND: ");
legendText.setPosition(RectangleEdge.BOTTOM);
chart.addSubtitle(legendText);