Java – add segment independent text to legend in JfreeChart piechart
Is there any way to include some arbitrary text in the legend in JfreeChart piechart? I know that a piesection label generator can be assigned to define the label of each pie chart part appearing on the chart legend
I want to insert some text in the legend, which has nothing to do with any pie chart part, such as "legend"
I'm building a 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 JfreeChart Addsubtitle(), hoping to position it directly above the legend, will only add a subtitle next to the chart title
Update 2: I've been trying to put texttitle in the wrapper of legendtitle, but it seems to be empty when the chart is built
LegendTitle legend = chart.getLegend(); BlockContainer container = legend.getWrapper(); container.add(new TextTitle("Legend"));
Adding "legend" text to decorate the legend is not that complicated
Solution
Check out org jfree. chart. From the source code of JfreeChart, we can see that addlegend () is just addsubtitle () behind the scenes. Everything indicates that addsubtitle () should be used to implement it
Check out org jfree. chart. JfreeChart adds part of its own legendtitle project. We can find the settings JfreeChart uses to place legend here
Therefore, the solution is to add a texttitle to the diagram in a similar way The relevant setting here is setposition (rectangle. Bottom)
TextTitle legendText = new TextTitle("This is LEGEND: "); legendText.setPosition(RectangleEdge.BOTTOM); chart.addSubtitle(legendText);