15

I am plotting very many points in Bokeh, and I have added the HoverTool to the list of tools of the figure, so that the mouse shows the x,y coordinates of the mouse when close to a glyph.

When the mouse gets close to a set of glyphs closely packed together, I get as many tooltips as glyphs. I want instead only one tooltip, the one of the closest glyph. This isn't just a presentation detail, because for very many points this results:

  • in slow interaction with the plot, with the browser getting stuck while all tooltips are generated
  • in a very long tooltip, where the same information is repeated as many times as many glyphs are close to the cursor

An example follows, with the code to replicate the behaviour: enter image description here

import numpy.random
from bokeh.plotting import figure, output_notebook, show
from bokeh.models import HoverTool
output_notebook()

hover = HoverTool()
hover.tooltips = [("(x,y)", "($x, $y)")]

x = numpy.random.randn(500)
y = numpy.random.randn(500)

p = figure(tools=[hover])
p.circle(x,y, color='red', size=14, alpha=0.4)

show(p)
gg349
  • 21,996
  • 5
  • 54
  • 64

6 Answers6

13

I was having a similar problem and came up with a solution using a custom tooltip. I insert a style tag at the top that only displays the first child div under the .bk-tooltip class, which is the first tooltip.

Here's a working example:

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

custom_hover = HoverTool()

custom_hover.tooltips = """
    <style>
        .bk-tooltip>div:not(:first-child) {display:none;}
    </style>

    <b>X: </b> @x <br>
    <b>Y: </b> @y
"""

p = figure(tools=[custom_hover]) #Custom behavior
#p = figure(tools=['hover'])  #Default behavior 

p.circle(x=[0.75,0.75,1.25,1.25], y=[0.75,1.25,0.75,1.25], size=230, color='red', fill_alpha=0.2)
p.y_range = Range1d(0,2)
p.x_range = Range1d(0,2)

show(p)

This is kind of a hacky solution, but it works in Safari, Firefox and Chrome. I think they'll be coming out with a more long-term solution soon.

pst0102
  • 146
  • 2
  • 4
  • By way of update there is an issue to add a user-configurable hook to limit hit test results scheduled for the 2.0 release later this year https://github.com/bokeh/bokeh/issues/9087 – bigreddot Nov 08 '19 at 17:43
6

The posted CSS solutions did not work for me with Bokeh 2.2.2. The following did:

    div.bk-tooltip.bk-right>div.bk>div:not(:first-child) {
        display:none !important;
    }
    div.bk-tooltip.bk-left>div.bk>div:not(:first-child) {
        display:none !important;
    }

Not the most elegant solution but it ended my frustration with 40 tooltips stacking vertically. This was implemented with an embedded chart on a website with custom CSS.

bachree
  • 128
  • 3
  • 11
4

Kudos to pst0101 for an excellent answer, which still works through 2018. Since the devs don't look like they'll be getting to this one any time soon, I thought I'd add a brief note about how to make pst's solution work for basic/standard tooltips, since it took me some trial and error to modify it on my own.

Since code is worth a thousand words, here is a stripped down version of my own:

hoverToolTip = [
        ("Item" + nbs + "Number/s", "@{ItemNumber}"),
        ("Description/s", "@{Description}{safe}"),
        ("Virtual" + nbs + "Item", """@{IsVirtual}
        <style>
            .bk-tooltip>div:not(:first-child) {display:none;}
        </style>""")
]

hover = HoverTool(tooltips=hoverToolTip)

nbs contains a unicode string of a non-breaking space, and {safe} tells bokeh it's safe to render html (specifically, line breaks) from my description field. Irrelevant to the question, but useful since hover has some broken wrapping behaviors with long text that many people will need to deal with.

  • 3
    There are many priorities, and few devs. The *only way* for things to get done faster is for more people to get involved. – bigreddot Jul 09 '18 at 15:51
  • 2
    Hey, I'm not criticizing. But since I don't have the time or skill to meaningfully contribute to the repository, I figure the next best thing is contributing my hacky workarounds to stack overflow. – Chris Brace Jul 18 '18 at 18:23
  • 1
    I can't get this to work. Has the HoverTool behaviour changed? I'm using Bokeh 2.2.3. – Dan Feb 12 '21 at 12:03
  • I'm also not able to get this working. Additionally, @ChrisBrace couldn't you add a declaration for nbs to your code snippet? It would make the example clearer. – lexXxel Apr 01 '21 at 12:54
4

I know that this may be old, but now there is a much better way to do this. And by better i mean that this method can be extended to any threshold number (like 4 tooltips). So, the steps:

  1. Define a CustomJSHover. In it you can write JS code. Also, you have access to all indices for current hover. In the code, you should set the threshold and delete other indices(will delete local copies). After this you should check if current index can be found in that list. If it is found, return an empty string, else - return a string with word hidden (will be used during html parsing)

     custom_hov = CustomJSHover(code="""
         special_vars.indices = special_vars.indices.slice(0,4)
         if (special_vars.indices.indexOf(special_vars.index) >= 0)
         {
             return " "
         }
         else
         {
             return " hidden "
         }
     """)
    

i)Add a HoverTool too your plot and define a html tooltip + define a formatter.
ii)For the html tooltip, add to main div a variable that will be mapped to our CustomJSHover. Let it be y. In our case, it will look like this <div @y{custom}>. (The {custom} is mandatory for mapped variables) The trick is that since our CustomJSHover will return 'hidden' when index will not be in indices, the entire tooltip will become hidden.

iii)For the formatters, you should add a dict mapping from your var (@y) to CustomJSHover. In our case: formatters={'@y':custom_hov}

figure.add_tools(HoverTool(tooltips=("""  
<div @y{custom}>
    <div>
        <img src='@image' alt='@image' style='float: top; width:128px;height:128px; margin: 5px 5px 5px 5px'/>
    </div>
    <div>
        <span style='font-size: 16px; color: #224499'>Some text</span>
        <span style='font-size: 18px'>@dataFrameText</span>
    </div>
</div>
"""), formatters={'@y':custom_hov}))

That's it. Now, only 4 tooltips will be displayed. You can change 4 to any number

Arron Stowne
  • 111
  • 3
2

Great solutions above. Special thanks to Chris Brace. I was having problems with tooltip in time series data where the number of data points was very high and subsampling was not possible. There were multiple tooltips showing due to closeness of circles. I needed to add tooltips separately to multiple glyphs which corresponded to specific columns in a pandas DataFrame. So i extended the solution from Chris Brace as follows (the applications requires column names to be dynamically selected during execution; unfortunately it was difficult to provide the complete code here but i though even this subset would help someone):

renderer = data_plot.circle(x=my_x_axis_col_name, y=my_y_axis_col_name, source=<my_data_source>, size=2)
hover_var = '@'+my_y_axis_col_name+"<style>.bk-tooltip>div:not(:first-child) {display:none;}</style>"
hover = HoverTool(renderers=[renderer], tooltips=[(my_y_axis_col_name, hover_var)])

There are better solutions expected in a future release of Bokeh. A gentle request to Bokeh developers to include a code snippet in the user guide as well when this is available.

Kumar Saurabh
  • 711
  • 7
  • 7
  • I can't get this to work. Has the HoverTool behaviour changed? I'm using Bokeh 2.2.3. – Dan Feb 12 '21 at 12:03
2

Credits to @bachree for his updated CSS code, which works with 2.3.0.
With that code you can simply add the following line, e.g. below your imports, to your jupyter notebook:

### your imports
from IPython.core.display import display, HTML
from bokeh.plotting import figure, output_notebook, show
from bokeh.models import HoverTool
output_notebook()
### end of imports

# fix bokeh showing multiple values on hover in notebooks
display(HTML("""
<style>
    div.bk-tooltip.bk-right>div.bk>div:not(:first-child) {
        display:none !important;
    }
    div.bk-tooltip.bk-left>div.bk>div:not(:first-child) {
        display:none !important;
    }
</style>
"""))

### your code

At the time of writing there has been no progress on bokeh's side and this still seems to be 'the way' to solve this.

mosc9575
  • 5,618
  • 2
  • 9
  • 32
lexXxel
  • 111
  • 2
  • 14