Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

python - Displaying only one tooltip when using the HoverTool() tool

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...