Bokeh: How to hide legends for lines that belong to the same group/category

Viewed 164

The scenario is the following: I have a set of data with 2 attributes: year and (export/import) There are 3 choices for years and 2 choices for (export/import) , counting in total 3*2=6 datasets.

 1. 2015, imports 
 2. 2016, imports
 3. 2017, imports
 4. 2015, exports
 5. 2016, exports
 6. 2017, exports 

How I used to do is to add a legend for each dataset, so that there are 6 legends in total. When I click on one legend, e.g. 2015 exports, only that 1 line is hiden. The other lines with the keyword, either 2015 or "exports" are still visible. I wonder whether there is a feasible way to generate only 2+3=5 legends, 2015,2016,2017,exports and imports. When I click on 2015, all 3 datasets that belong to 2015 are hidden. Then, if I then further click on "imports", than all datasets that belong to "imports" are hidden. At this point, only 2 datasets are visible:

 1. 2016, exports
 2. 2016, imports

(The reasoning is 1. It grows linearly 2. It gives another angle of insight to the dataset)

I have a working example of current situation with 6 legends:

from bokeh.io import output_file, show, output_notebook, reset_output
from bokeh.models import ColumnDataSource
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure

output_file("stacked_split.html")

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]

exports = {'fruits' : fruits,
           '2015'   : [2, 1, 4, 3, 2, 4],
           '2016'   : [5, 3, 4, 2, 4, 6],
           '2017'   : [3, 2, 4, 4, 5, 3]}
imports = {'fruits' : fruits,
           '2015'   : [-1, 0, -1, -3, -2, -1],
           '2016'   : [-2, -1, -3, -1, -2, -2],
           '2017'   : [-1, -2, -1, 0, -2, -2]}

p = figure(y_range=fruits, plot_height=250, x_range=(-16, 16), title="Fruit import/export, by year",
           toolbar_location=None)

p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
             legend=["%s exports" % x for x in years])

p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend=["%s imports" % x for x in years])

p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.click_policy = 'hide'
reset_output()
output_notebook()
show(p)

strong text

0 Answers
Related