jfreechart - change sample of colors in legend
Asked Answered
D

2

4

Can someone tell me how to change samples of series color in legend in jfreechart. What I have now is small line of series color eg:
Example
I would like to have square sample of those colors. Here is an example
Example

Can someone help me?

Ok I found the solution. At least I think. Of course there is no simple way to do this. There is now, you know, setShape(square) method, that will do the trick, at least i haven't found one.

Basicly XY chart and time chart have "line style" legend by default in contrary to bar chart for example (if has square legend by default). So I had to remove current legend and create new one with square samples of color and this new legend add to my time chart.

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

Thanks for attention. I hope it will help someone.

Detonator answered 5/9, 2011 at 10:42 Comment(1)
Please provide an sscce that shows your current result.Biomedicine
D
3

Generating your own legend, as you do above, is a perfectly acceptable way of doing things in JFreeChart. If you didn't want to do it, you can also define your own renderer with the lookupLegendShape() method overridden.

thePlot.setRenderer(new XYLineAndShapeRenderer()
      {
         public Shape lookupLegendShape(int series)
         {
            return new Rectangle(15, 15);
         }
      });
Diversiform answered 16/11, 2011 at 2:7 Comment(0)
S
0

If you use a XYBarRenderer Class XYBarRenderer

(Subclasses: ClusteredXYBarRenderer, StackedXYBarRenderer)

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

Example:

JFreeChart chart = ChartFactory.createXYBarChart(/*...*/);

XYPlot plot = (XYPlot) chart.getPlot();

ClusteredXYBarRenderer renderer = new ClusteredXYBarRenderer();
renderer.setLegendBar(new Rectangle(17, 17));

plot.setRenderer(renderer);
Stokehole answered 22/1, 2015 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.