Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas + bokeh - How get dataframe column name for hover tool

I plot lines from some columns of a dataframe. I would like the hover tool to display the name of the column that originated that data and also some information from other columns not plotted.

For example, in the code below I would like the hover tool to display "Name = A; Aux = 0.1" when the mouse is over the central point on line A. This value is stored in column A1. Conversely, when over the central point on line B the tool should display "Name = B; Aux = 0.3"

from bokeh.io import show
from bokeh.models import  HoverTool, ColumnDataSource
from bokeh.plotting import figure
import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3], 'A' : [1, 5, 3], 'A1': [0.2, 0.1, 0.2],
                  'B' : [2, 4, 3], 'B1':[0.1, 0.3, 0.2]})

tools_to_show = 'box_zoom,save,hover,reset'
p = figure(plot_height =300, plot_width = 1200, 
           toolbar_location='above',
           tools=tools_to_show)

columns = ['A', 'B']
source = ColumnDataSource(df)
for col in columns:
    p.line('x', col, source=source)

hover = p.select(dict(type=HoverTool))
hover.tooltips = [("Name","@col"), ("Aux", "@col1")]
hover.mode = 'mouse'

show(p)

Thanks!

like image 712
RMelo Avatar asked Sep 17 '25 06:09

RMelo


1 Answers

There is a recent feature to support this. With Bokeh 0.13.0 or newer, you can set the name on a glyph and refer to that name in a tooltip with $name. Additionally, you can refer to a column with that name with @$name. However, the "indirection" column has to be the one specified in name, so you will have to re-arrange your column names to this expectation:

from bokeh.io import show
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3], 'A_y' : [1, 5, 3], 'A': [0.2, 0.1, 0.2],
                  'B_y' : [2, 4, 3], 'B':[0.1, 0.3, 0.2]})

tools_to_show = 'box_zoom,save,hover,reset'
p = figure(plot_height =300, plot_width = 1200,
           toolbar_location='above', tools=tools_to_show,

           # "easy" tooltips in Bokeh 0.13.0 or newer
           tooltips=[("Name","$name"), ("Aux", "@$name")])

columns = ['A', 'B']
source = ColumnDataSource(df)
for col in columns:

    # have to use different colnames for y-coords so tooltip can refer to @$name
    p.line('x', col + "_y", source=source, name=col)

show(p)

enter image description here

like image 72
bigreddot Avatar answered Sep 19 '25 20:09

bigreddot