Search code examples
pythontooltipbokeh

How to show column names in tooltip in Bokeh


I cannot find a way how to place a series name in a tooltip instead of ???. Here is a simple code that I tried and the output:

from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool

x_data = [[2,4,6,8], [2,4,6,8]]
y_data = [[2,5,9,6], [5,7,6,2]]
names = ['y1', 'y2']

output_file('index.html')

p = figure(plot_width=300, plot_height=200)

p.multi_line(x_data, y_data)

p.add_tools(HoverTool(tooltips=[
    ('Name', '@names')
]))

show(p)

enter image description here

I tried several formats of names list (or list of lists), but no success.

Do you have any idea?


Solution

  • Based on the scatter plot example in the documentation (here), it looks like the way to go is to create a dictionnary with all the keys and values that you need for your plot and hover tool. And create a ColumnDataSource based on this dictionary. See code below:

    from bokeh.plotting import figure, output_file, show, ColumnDataSource
    from bokeh.models import HoverTool
    
    source=ColumnDataSource({'x_data':[[2,4,6,8], [2,4,6,8]],'y_data':[[2,5,9,6], [5,7,6,2]],'names':['y1', 'y2']})
    
    output_file('index.html')
    
    p = figure(plot_width=300, plot_height=200)
    
    p.multi_line('x_data', 'y_data',source=source)
    
    p.add_tools(HoverTool(tooltips=[('Name', '@names')]))
    
    show(p)
    

    And the result shows the correct tooltips:

    enter image description here