Is it possible to add Legend to the plot in JFreeChart?

rmartinus picture rmartinus · Jun 30, 2010 · Viewed 12k times · Source

I'm trying to add a legend under the plot in scattered chart as shown below. Anyone knows if this is possible?

Before: alt text

After: alt text

Answer

rmartinus picture rmartinus · Jul 1, 2010

Here's the custom label generator that I created:

public class LegendXYItemLabelGenerator extends StandardXYItemLabelGenerator
        implements XYItemLabelGenerator, Cloneable, PublicCloneable,
        Serializable {
    private LegendItemCollection legendItems;

    public LegendXYItemLabelGenerator(LegendItemCollection legendItems) {
        super();
        this.legendItems = legendItems;
    }

    @Override
    public String generateLabel(XYDataset dataset, int series, int item) {
        LegendItem legendItem = legendItems.get(series);
        return legendItem.getLabel();
    }
}

and then I added this code in addition to @Guilaume's code:

renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelGenerator(new LegendXYItemLabelGenerator(plot.getLegendItems()));

and here's the result:

alt text