Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jFreeChart: How to hide items from legend?

Tags:

jfreechart

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

like image 539
tzippy Avatar asked Jul 27 '10 09:07

tzippy


2 Answers

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.

like image 158
Jason Avatar answered Oct 17 '22 06:10

Jason


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));
like image 35
tzippy Avatar answered Oct 17 '22 07:10

tzippy