How to pass a Python value to a HoverTool

I have a Bokeh visualization with a HoverTool that works well and now I want to pass a Python value into the HoverTool for informational purposes. I’ve tried several approaches … that haven’t worked well.

I thought I could include a Python variable as a dict element and then access it in the tooltips list. Now I think that’s not quite right and that I need to create a Model and pass that to the HoverTool.

So I’m looking for a simple example of how to pass a Python value to a HoverTool.



Hello @highpost more information is needed. Is this a Bokeh server application? Standalone HTML/JS output? What exactly does “pass a Python value into the HoverTool” actually mean? (I can imagine several possibilities but have no idea which is correct—you need to be specific and detailed about what you want to accomplish) And what are the approaches you mentioned? It’s always advised to try to include a Minimal Reproducible Example to focus the discussion as much as possible, which helps others help you.

I’m sorry for my lack of specificity. I’m using Bokeh in a Jupyter notebook inside VS Code and I’ve included a basic working example below. Now I have a Python variable named myindex and I want to pass its value into the tooltips list for my visualization’s (default) HoverTool. I don’t expect it to be updated if its value changes in Python (which it won’t).

I read the documentation and searched for examples, but I didn’t get anything close to working.

from numpy          import array
from       import output_notebook, show
from bokeh.models   import CustomJSHover, HoverTool
from bokeh.palettes import Greys256
from bokeh.plotting import figure

myindex = 4
myimage = array([[0.0, 0.5], [0.5, 0.0]])
p1 = figure(x_range = (0, 2),
            y_range = (0, 2),
            tooltips  = [
                          ("x, y",      "$x, $y"),
                          ("sx, sy",    "$sx, $sy"),
                          ("index",     "myindex value here"),
                          ("value",     "@image")
p1.image(image = [myimage], x = 0, y = 0, dw = 2, dh = 2, palette = Greys256)

Thanks for your help.

@highpost unless I am misunderstanding your question, you can use standard Python string substitution

("index", f"{myindex}"),

The value string may contain any number of Bokeh-specific formatting substitutions, e.g @foo or $sx, etc. But it does not have to contain any at all, and everything that is not a (Bokeh) formatting substitution is simply displayed as-is.

Yes, of course. :flushed: Thanks so much for your help!

1 Like