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
451 views
in Technique[技术] by (71.8m points)

python - HoverTool for multiple data series in bokeh scatter plot

I have the following small example script making use of numpy and bokeh:

import numpy as np
import bokeh.plotting as bp
from bokeh.objects import HoverTool 
bp.output_file('test.html')

fig = bp.figure(tools="reset,hover")
x = np.linspace(0,2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
s1 = fig.scatter(x=x,y=y1,color='#0000ff',size=10,legend='sine')
s1.select(dict(type=HoverTool)).tooltips = {"x":"$x", "y":"$y"}
s2 = fig.scatter(x=x,y=y2,color='#ff0000',size=10,legend='cosine')
s2.select(dict(type=HoverTool)).tooltips = {"x":"$x", "y":"$y"}
bp.show()

The problem is that the hover tool only works for the cosine curve but not for the sine.

I know that one option would be to plot both series togehter and change the color of the cosine data points:

import numpy as np
import bokeh.plotting as bp
from bokeh.objects import HoverTool 
bp.output_file('test.html')

fig = bp.figure(tools="reset,hover")
x = np.linspace(0,2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

x = np.array([x,x]).flatten()
y = np.array([y1,y2]).flatten()

blue = np.array('#0000ff').flatten()
red = np.array('#ff0000').flatten()
colors = np.array([blue.repeat(len(y1)),red.repeat(len(y1))]).flatten()

s1 = fig.scatter(x=x,y=y,color=colors,size=10,legend='sine & cosine')
s1.select(dict(type=HoverTool)).tooltips = {"x":"$x", "y":"$y"}
bp.show()

But then I loose the legend entry for the second color.

How do I manage to be able to hover over both data sets and see the corresponding tooltip?

Thanks!

Max

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Edit: Note that the approach below is necessary only if you want different tooltips for different glyphs. If you want the same tooltips for all glyphs, see the answer above.


If you want to have multiple hover tools, you need to add multiple hover tools, each configured for a different renderer. You can add them this way:

p = figure()

r1 = p.circle([1,2,3], [4,5,6], color="blue")
p.add_tools(HoverTool(renderers=[r1], tooltips=TIPS))

r2 = p.square([4,5,6], [1,2,3], color="red")
p.add_tools(HoverTool(renderers=[r2], tooltips=TIPS))

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

...