16

我有以下使用 numpy 和 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()

问题是悬停工具仅适用于余弦曲线而不适用于正弦曲线。

我知道一种选择是将两个系列绘制在一起并更改余弦数据点的颜色:

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()

但后来我松开了第二种颜色的图例条目。

我如何设法将鼠标悬停在两个数据集上并查看相应的工具提示?

谢谢!

最大限度

4

2 回答 2

33

编辑:请注意,仅当您希望为不同的字形提供不同的工具提示时,才需要使用以下方法。如果您希望所有字形都使用相同的工具提示,请参阅上面的答案。


如果您想拥有多个悬停工具,则需要添加多个悬停工具,每个工具都配置为不同的渲染器。您可以通过以下方式添加它们:

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))
于 2015-12-30T18:23:27.310 回答
13

最初的答案是古老而过时的,这里是如何使用任何现代版本的散景来实现这一点:

from bokeh.plotting import figure, show
import numpy as np

x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)

fig = figure(tools="reset", tooltips=[("x", "$x"), ("y", "$y")])
s1 = fig.scatter(x, y1, color='#0000ff', size=10, legend_label='sine')
s2 = fig.scatter(x, y2, color='#ff0000', size=10, legend_label='cosine')

show(fig)
于 2014-12-18T14:49:22.727 回答