Search code examples
javagraphlegendjfreechartpoints

JFreeChart how to manually add the legend into plot graph


I have used JFreeChart library in java to draw one line with points ie. plot.

The points have two kind of color - green or blue. Below is some sample with different colors. I would like to display two legend for this one single line because of different color. Is it possible?

I know that with two lines (green and blue) this should be simply solved with two legends but this is not our case. With this approach the JFreeChart offers some option to automatically generate the legends as below code.

private void myMethod () {
 JFreeChart j = new JFreeChart(title, titleFont, plot, createLegend);
}

Thanks.

enter image description here


Solution

  • Here is some possible solution how to add static legend.

    public void test() {
        //XYPlot p1 = new XYPlot(null, new NumberAxis("Domain Axis"),
        //        new NumberAxis("Range Axis"), new StandardXYItemRenderer());
        XYPlot categoryPlot = chart.getXYPlot();
    
        LegendItemCollection c1 = categoryPlos.getLegendItems();
        c1.add(new LegendItem("X"));
        p1.setFixedLegendItems(c1);
      
    
    }
    
    

    Resource: https://www.programcreek.com/java-api-examples/?api=org.jfree.chart.LegendItem