Jfreechart - change the color swatch in a legend

Can someone tell me how to change the color swatches of a series in a legend in jfreechart. Now I have a small series color string, for example:
Example
I would like to have a square pattern of these colors. Here is an example
Example

Can someone help me?

Ok, I found a solution. At least I think. Of course, there is no easy way to do this. Now you know the setShape (square) method that will do the trick, at least I did not find it.

Basically, the XY chart and timeline have a "line style" legend by default, unlike a histogram, for example (if it has a square legend by default). So I had to delete the current legend and create a new one with square color swatches, and this new legend will add my timeline.

LegendItemCollection legend = new LegendItemCollection(); for (int i = 0; i < seriecCount; ++i) { chart.getXYPlot().getRenderer().setSeriesPaint(i, colorPalette.get(i)); LegendItem li = new LegendItem(data.getSeriesName(i), "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, colorPalette.get(i)); legend.add(li); } chart.getXYPlot().setFixedLegendItems(legend); 

Thank you for attention. Hope this helps someone.

+4
source share
2 answers

Creating your own legend, as you do above, is a perfectly acceptable way of doing things in JFreeChart. If you do not want to do this, you can also define your own renderer with an overridden lookupLegendShape () method.

 thePlot.setRenderer(new XYLineAndShapeRenderer() { public Shape lookupLegendShape(int series) { return new Rectangle(15, 15); } }); 
+3
source

If you use XYBarRenderer class XYBarRenderer

(Subclasses: ClusteredXYBarRenderer, StackedXYBarRenderer)

You can use XYBarRenderer.setLegendBar (java.awt.Shape bar),
See: Javadoc
to get good squares.

Example:

 JFreeChart chart = ChartFactory.createXYBarChart(/*...*/); XYPlot plot = (XYPlot) chart.getPlot(); ClusteredXYBarRenderer renderer = new ClusteredXYBarRenderer(); renderer.setLegendBar(new Rectangle(17, 17)); plot.setRenderer(renderer); 
0
source

All Articles