HoverTool用于散景散点图中的多个数据系列

Max*_*Max 13 python bokeh

我有以下小例子脚本使用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()
Run Code Online (Sandbox Code Playgroud)

问题是悬停工具仅适用于余弦曲线,但不适用于正弦曲线.

我知道一个选项是绘制两个系列,并更改余弦数据点的颜色:

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()
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

马克斯

big*_*dot 26

如果要使用多个悬停工具,则需要添加多个悬停工具,每个工具都配置为不同的渲染器.您可以这样添加它们:

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))
Run Code Online (Sandbox Code Playgroud)

  • 这应该添加到已接受的答案中。这是(到目前为止)为每个绘图而不是每个图形设置不同悬停渲染器的正确方法。 (2认同)
  • 然而,这会导致绘图有两个不同的“悬停”图标。有没有办法统一这个(例如用一个图标来切换两者)?或者,是否可以将“悬停”按钮重命名为更明确的名称? (2认同)

Dam*_*ila 11

这实际上是master中解决的bug.我修复了这个PR https://github.com/bokeh/bokeh/pull/1511 您可以按照以下说明安装包含修复程序的devel构建:http://bokeh.pydata.org/docs/installation.html#开发人员构建

此外,您需要修改第一个代码以使用模型而不是第三行中的对象,如下所示:

import numpy as np
import bokeh.plotting as bp
from bokeh.models 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')
fig.select(dict(type=HoverTool)).tooltips = {"x":"$x", "y":"$y"}
bp.show()
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

干杯.

达米安

更新以下评论

  • 我收到此错误:AttributeError:'generator'对象没有属性'工具提示'.我使用以下命令更新了我的散景:pip install --pre -i https://pypi.anaconda.org/bokeh/channel/dev/simple bokeh --extra-index-url https://pypi.python.org/简单/ (5认同)