要解决Bokeh 1.0.4版本中交互式图例不包括所有图形的问题,可以使用自定义的回调函数来控制图例的显示和隐藏。以下是一个示例代码:
from bokeh.plotting import figure, show
from bokeh.models import CustomJS, Legend
from bokeh.layouts import row
# 创建一个包含多个图形的图表
p = figure(width=400, height=400)
line1 = p.line([1, 2, 3], [1, 2, 3], line_color="red", line_width=2, legend="Line 1")
line2 = p.line([1, 2, 3], [3, 2, 1], line_color="blue", line_width=2, legend="Line 2")
line3 = p.line([1, 2, 3], [2, 1, 3], line_color="green", line_width=2, legend="Line 3")
# 创建一个空的图例
legend = Legend(items=[])
# 创建一个回调函数,控制图例的显示和隐藏
callback = CustomJS(args=dict(legend=legend, line1=line1, line2=line2, line3=line3), code="""
// 获取选中的图形
var selected = cb_obj.active;
// 隐藏所有图例
legend.items = [];
// 根据选中的图形显示相应的图例
if (selected.includes(0))
legend.items.push(line1);
if (selected.includes(1))
legend.items.push(line2);
if (selected.includes(2))
legend.items.push(line3);
// 更新图表
legend.plot.plot_view.request_render();
""")
# 创建一个多选框,用于选择图形
checkbox = CheckboxGroup(labels=["Line 1", "Line 2", "Line 3"], active=[0, 1, 2], callback=callback)
# 将图表和图例放在一个布局中
layout = row(p, checkbox, legend)
# 显示图表
show(layout)
在上面的示例代码中,我们首先创建了一个包含多个图形的图表。然后,我们创建了一个空的图例,并定义了一个回调函数来控制图例的显示和隐藏。回调函数根据多选框选择的图形来更新图例的内容,并通过legend.plot.plot_view.request_render()
更新图表。最后,我们将图表、多选框和图例放在一个布局中,并显示图表。
通过这种方式,我们可以根据需要选择显示或隐藏特定的图形,并相应地更新图例。