Search code examples
javauser-interfacejfreechart

How to customize legend of a BoxAndWhisker plot


I've created a BoxAndWhiskerRenderer plot using JFreeChart and it seems that it is automatically creating a sort of legend (see attached picutre).

enter image description here

Is there a way to remove the outside border of this legend and customize the font of the labels in the legend items?

Here is an example of my code:

//Get the desired BoxAndWhiskerCategoryDataset from a LinkedHashMap
BoxAndWhiskerCategoryDataset dataset = values.get(b);

//Create X axis
CategoryAxis xAxis = new CategoryAxis();
xAxis.setAxisLineVisible(false);

//Create Y axis
NumberAxis yAxis = new NumberAxis(b.getLabel());
yAxis.setAxisLineVisible(false);
yAxis.setTickLabelFont(FDFont.getFont(12f));
yAxis.setLabelFont(FDFont.getFont());
yAxis.setLabelPaint(FDPalette.secondaryText);
yAxis.setTickLabelPaint(FDPalette.secondaryText);
yAxis.setAutoRangeIncludesZero(false);

//Create renderer
BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
int count = 0;
for(Map.Entry<Integer,Color> map : clusterColor.entrySet()){
    //Set color for the series (I have a previously created map which links colors and series)
    renderer.setSeriesPaint(count,map.getValue());
    count++;
}
renderer.setFillBox(true);
renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);

JFreeChart chart = new JFreeChart(plot);
chart.setBackgroundPaint(white);
chart.setBorderVisible(false);

ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(300, 270));

Solution

  • As shown here, the simplest JFreeChart constructor adds a legend by default. The code for doing so is seen here; simply substitute your desired frame, color and position.

    Starting from this example, the following changes produce the chart shown below:

    private void createChartPanel() {
        …
        JFreeChart chart = new JFreeChart("BoxAndWhiskerDemo", plot);
        LegendTitle legend = chart.getLegend();
        legend.setFrame(new LineBorder(Color.white, new BasicStroke(1.0f),
            new RectangleInsets(1.0, 1.0, 1.0, 1.0)));
        legend.setItemFont(legend.getItemFont().deriveFont(16f));
        chartPanel = new ChartPanel(chart);
    }
    

    image

    Compare to this default legend:

    image