cmfrantz
cmfrantz

Reputation: 61

Displaying only one tooltip when using the hovertool in Bokeh

This is my first stackoverflow question so I apologize for the duplicate post; I don't have the reputation to comment on the original thread and wasn't sure how else to ask this question.

I have a plot with a hover tooltip that frequently displays a long list of returned values. I just want one (any one) to be displayed if there are overlapping values.

Screenshot of bokeh plot with many hover tooltips

I've tried several of the CSS solutions posted on the original thread, but still get multiple tooltips displayed. I'm not sure if I'm implementing the code snippets wrong, or if the solutions are no longer working.

Screenshot of basic plot from the original post showing the undesired behavior of multiple hover tooltips

I'm using bokeh 2.3.3 and Chrome. Basic code example is below, and the final project I'm trying to get working is here.

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

custom_hover = HoverTool()

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


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

p = figure(tools=[custom_hover]) #Custom 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)

Thanks for the help!

Upvotes: 6

Views: 1543

Answers (1)

mosc9575
mosc9575

Reputation: 6367

The solution below allows only one visible tooltip. This can be changed by modifying the parameter num.

This solution was tested with Bokeh 2.3.2.

from bokeh.plotting import figure, show, output_notebook
from bokeh.models import HoverTool, Range1d, CustomJSHover
output_notebook()

p = figure(tools='')
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 = p.x_range = Range1d(0,2)

t = """
<div @x{custom}>
    <b>X: </b> @x <br>
    <b>Y: </b> @y
</div>
"""

# define how many tooltips you want to show as maximum
num = 1

f = CustomJSHover(code=f"""
special_vars.indices = special_vars.indices.slice(0,{num})
return special_vars.indices.includes(special_vars.index) ? " " : " hidden "
""")

p.add_tools(HoverTool(tooltips=t, formatters={'@x': f}))

show(p)

Upvotes: 2

Related Questions