JFreeChart Legend Display

2019-01-28 01:30发布

In my JFreeChart timeseries plots I find the legends lines to thin to see the colour accurately. Another post [ jfreechart - change sample of colors in legend ] suggested overriding a renderer method as follows:

renderer = new XYLineAndShapeRenderer()
{
    private static final long serialVersionUID = 1L;
    public Shape lookupLegendShape(int series)
    {
        return new Rectangle(15, 15);
    }
};

this approach works fine until you do what I did

renderer.setSeriesShapesVisible(i, false);

Once I did that the legend reverts back to a line. Is there any way round this?

The solution I adopted is close to that suggested by TrashGod I overrode the getLegendItem() method, forcing the legend shape to the desired box.

    renderer = new XYLineAndShapeRenderer()
    {
        private static final long serialVersionUID = 1L;

        public LegendItem getLegendItem(int datasetIndex, int series)
        {
            LegendItem legend = super.getLegendItem(datasetIndex, series);
            return new LegendItem(legend.getLabel(), legend.getDescription(), legend.getToolTipText(), legend.getURLText(), Plot.DEFAULT_LEGEND_ITEM_BOX, legend.getFillPaint());
        }
    };

2条回答
我想做一个坏孩纸
2楼-- · 2019-01-28 02:02

Get the renderer and do the following:

XYItemRenderer renderer = plot.getRenderer();
BasicStroke thickLine = new BasicStroke( 4.0f ); 
renderer.setSeriesStroke(0, thickLine); 

This will make your line thicker.

查看更多
神经病院院长
3楼-- · 2019-01-28 02:20

You're going to have to override getLegendItem() to get the LegendItem you want in place of the one the renderer creates.

Addendum: Here's a simple example that should help you get started.

XYPlot plot = (XYPlot) chart.getPlot();
plot.setRenderer(new MyRenderer());
...
private static class MyRenderer extends XYLineAndShapeRenderer {

    @Override
    public LegendItem getLegendItem(int dataset, int series) {
        LegendItem legendItem = super.getLegendItem(dataset, series);
        System.out.println(dataset + " " + series + " " + legendItem.getShape());
        // modify legendItem here
        return legendItem;
    }
}
查看更多
登录 后发表回答