散景:figure.line 的 hovertool 自定义回调

bokeh: custom callback for hovertool for figure.line

我正在尝试编写一个代码,在 figure.line 对象上添加执行客户 js 代码的 hovertool。为了做到这一点,我使用用户指南代码作为示例 (https://docs.bokeh.org/en/latest/docs/user_guide/interaction/callbacks.html#customjs-for-hover),但进行了简化和修改(见下文)。我发现它适用于 figure.segment 但不适用于 figure.line.

这是完整的例子:

from bokeh.models import CustomJS, HoverTool
from bokeh.plotting import figure, output_file, show

output_file("hover_callback.html")

# define some points and a little graph between them
x = [2, 3, 5, 6, 8, 7]
y = [6, 4, 3, 8, 7, 5]

p = figure(plot_width=400, plot_height=400, tools="", toolbar_location=None)

lines = p.line(x, y, line_color='blue', line_width=5)
seg = p.segment(x[0:3], y[0:3], x1=x[3:], y1=y[3:], color='olive', alpha=0.6, line_width=3)

code = """
const indices = cb_data.index.indices
if (indices.length > 0) {
    console.log('Hello!')
}
"""

callback = CustomJS(code=code)
p.add_tools(HoverTool(tooltips=None, callback=callback, renderers=[lines, seg]))

show(p)

cb_data.index.indices 当我将指针放在线段(橄榄色)而不是线(蓝色)上时,它不是空的。

这是一种预期的行为吗?如果是这样,我将不胜感激参考一些解释过的文档。谢谢!

您也可以为线条激活悬停工具。但是你必须对你的 JavaScript 进行相当多的调整。第return行索引的信息有点不同,你要问const line_indices = cb_data.index.line_indices.

这是您的完整示例:

from bokeh.models import CustomJS, HoverTool
from bokeh.plotting import figure, output_file, show

output_file("hover_callback.html")

# define some points and a little graph between them
x = [2, 3, 5, 6, 8, 7]
y = [6, 4, 3, 8, 7, 5]

p = figure(plot_width=400, plot_height=400, tools="", toolbar_location=None)

lines = p.line(x, y, line_color='blue', line_width=5)
seg = p.segment(x[0:3], y[0:3], x1=x[3:], y1=y[3:], color='olive', alpha=0.6, line_width=3)

code = """
const indices = cb_data.index.indices
const line_indices = cb_data.index.line_indices
if (indices.length +  line_indices.length > 0) {
    console.log('Hello!')
}
"""

callback = CustomJS(code=code)
p.add_tools(HoverTool(tooltips=None, callback=callback, renderers=[lines, seg]))

show(p)