7

I need to hide every second/third/forth item from the legend. IS there a way to achieve this in jFreeChart? thanks!

tzippy
  • 6,458
  • 30
  • 82
  • 151

2 Answers2

8

I have tried the above suggestion but it didn't seem to work for me. If you just want to remove series from the legend you can do it with the setSeriesVisibleInLegend() method. My scenario was that some of my series do not have a legend key. If they don't have a legend key then the series shouldn't be visible in the legend. I implemented this with the following code:

    for(int i = 0; i < seriesList.size(); i++){

        if(seriesList.get(i).getKey() == null || seriesList.get(i).getKey().equals("")){
            graph.getXYPlot().getRenderer().setSeriesVisibleInLegend(i, Boolean.FALSE);
        }
    }

The seriesList is a list of seriesData pojo's that I created that holds all of the graph data to create the graph. If the seriesData object's key value is null or = "" then the series will not be visible in the legend.

tkanzakic
  • 5,499
  • 16
  • 34
  • 41
Jason
  • 81
  • 1
  • 2
4

okay, just did it myself. This way I remove every second item from the legend. please leave comments!

LegendItemCollection legendItemsOld = plot.getLegendItems();
final LegendItemCollection legendItemsNew = new LegendItemCollection();

for(int i = 0; i< legendItemsOld.getItemCount(); i++){
  if(!(i%2 == 0)){
    legendItemsNew.add(legendItemsOld.get(i));
  }
}
LegendItemSource source = new LegendItemSource() {
LegendItemCollection lic = new LegendItemCollection();
{lic.addAll(legendItemsNew);}
public LegendItemCollection getLegendItems() {  
    return lic;
}
};
chart.addLegend(new LegendTitle(source));
tzippy
  • 6,458
  • 30
  • 82
  • 151
  • 2
    That's good for a dynamic solution. It's also possible to use renderer.getLegendItems() and plot.setFixedLegendItems(). This yields a simpler solution, but is only good if your legend won't be changing after you set the fixed legend. I don't have time to craft the details of the solution, but look for getLegendItems and setFixedLegendItems in AbstractXYItemRenderer and XYPlot. – Jason Aug 28 '12 at 20:05