Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 913
rmartinus Avatar asked Jun 30 '10 06:06

rmartinus


2 Answers

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

like image 86
rmartinus Avatar answered Oct 13 '22 00:10

rmartinus


Extending StandardXYItemLabelGenerator is often a useful approach, but the supplied constructors may suffice. For this generator, the MessageFormat ArgumentIndex values correspond to the series name, domain and range.

NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(2); // etc.
XYItemLabelGenerator generator =
    new StandardXYItemLabelGenerator("{0} {1} {2}", format, format);
renderer.setBaseItemLabelGenerator(generator);
renderer.setBaseItemLabelsVisible(true);

In addition, you can control individual series labeling with

renderer.setSeriesItemLabelsVisible(true);
like image 33
trashgod Avatar answered Oct 12 '22 23:10

trashgod