首页 > 解决方案 > 我想在散景 python 中单击选择和取消选择曲线

问题描述

我想在 bokeh/Python3.x/jupyter 中单击一次来选择或取消选择所有曲线,我创建了一个全选按钮,只需单击一次即可完成这项工作,但不知道如何调用它。

from bokeh.io import output_notebook, show
from bokeh.plotting import figure
from bokeh.palettes import Dark2_5 as palette
from bokeh.layouts import widgetbox, row, column
from bokeh.models import Button,CheckboxButtonGroup, CustomJS
import itertools
import numpy as np

# create a new plot (with a title) using figure
p = figure(plot_width=800, plot_height=400, title="My Line Plot")

start = 10.0
x = range(20)
colors = itertools.cycle(palette) 
nseries = 50

# add a line renderer
for n in range(nseries):
    y = np.cumsum(np.random.randn(1,20))
    p.line(x, y, line_width=1, legend=str(n), color=next(colors), name=str(n))

p.legend.location = "top_left"
p.legend.click_policy="hide"
select_all = Button(label="select all")
checkbox_button_group = CheckboxButtonGroup(
        labels=[str(n) for n in range(nseries)], active=[])

code = """
active = cb_obj.active;
rend_list = fig.renderers;
for (rend of rend_list) {
    if (rend.name!==null) {
        rend.visible = !active.includes(Number(rend.name));
    }
}
"""

checkbox_button_group.callback = CustomJS(args={'fig':p},code=code)

show(column([p, select_all,checkbox_button_group]))

标签: jquerypython-3.xjupyter-notebookbokeh

解决方案


一种解决方案是checkbox_button_group.active清空并触发其回调。在之前添加以下行show...

select_all_code = """
checkbox_button_group.active=[]
callback.execute(checkbox_button_group, { fig })
"""
select_all.callback = CustomJS(args=dict(checkbox_button_group=checkbox_button_group,
                                        fig=p,
                                        callback=checkbox_button_group.callback), 
                                code=select_all_code)

可能有一个更优雅的解决方案。


推荐阅读