Search code examples
pythonbokeh

Add hover to plot with multiple vertical bars Bokeh


So I essentially followed the example on the bokeh documentation site about handling categorical data:

https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html

Which ended me up with this code (I simplified it a little):

# dictionary with data for making a figure
data = {'continents' : continents,
        '2016' : list2016,
        '2017' : list2017,
        '2018' : list2018 }


source = ColumnDataSource(data=data)

p = figure(x_range=continents, y_range=(0, 450), plot_height=250, title="University count per continent per year",
           toolbar_location=None, tools="")

p.vbar(x=dodge('continents', -0.25, range=p.x_range), top='2016', width=0.2, source=source,
       color="#c9d9d3", legend=value("2016"))

p.vbar(x=dodge('continents',  0.0,  range=p.x_range), top='2017', width=0.2, source=source,
       color="#718dbf", legend=value("2017"))

p.vbar(x=dodge('continents',  0.25, range=p.x_range), top='2018', width=0.2, source=source,
       color="#e84d60", legend=value("2018"))

p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.legend.location = "top_right"
p.legend.orientation = "horizontal"

Where the data column has 4 keys, with continents being the "categories" and 2016, 2017 and 2018 being a list of values corresponding to every continent in the continents list. So for example:

continents = ["Africa", "Europe"]
list2016 = ["1", "3"] 
list2017 = ["4", "2"]
list2018 = ["14", "3"]

So this basically that Africa had 1, 4 and 14 things of something in 2016, 2017 and 2018 respectively. Now what I would like to do is add hover to these different vertical bars so that if I hover of some bar it gives me the count numerically for that year/continent. Would this be possible?


Solution

  • Since 0.13, you can give each glyph a name value then refer to that in tooltips as $name. Additionally you can look up from a column with that name by using @$name. You can also pass tooltips to figure directly as a convenience. All together:

    p = figure(x_range=continents, y_range=(0, 20), plot_height=250,
               title="University count per continent per year",
               toolbar_location=None, tools="hover", 
               tooltips="@continents $name: @$name")
    
    p.vbar(x=dodge('continents', -0.25, range=p.x_range), top='2016', width=0.2, source=source,
           color="#c9d9d3", legend=value("2016"), name="2016")
    
    p.vbar(x=dodge('continents',  0.0,  range=p.x_range), top='2017', width=0.2, source=source,
           color="#718dbf", legend=value("2017"), name="2017")
    
    p.vbar(x=dodge('continents',  0.25, range=p.x_range), top='2018', width=0.2, source=source,
           color="#e84d60", legend=value("2018"), name="2018")
    

    enter image description here