0

我正在尝试编写一个代码来添加悬停工具,在figure.line对象上执行客户 js 代码。为了做到这一点,我使用用户指南代码作为示例(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当我将指针放在段(橄榄色)而不是线(蓝色)上时,它不为空。 在此处输入图像描述

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

4

1 回答 1

1

您也可以为线条激活 HoverTool。但是你必须相当多地调整你的 JavaScript。行返回索引的信息有点不同,你必须要求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)
于 2020-11-30T22:15:03.833 回答