散景图的已选中复选框的数量限制

时间:2018-06-27 16:06:20

标签: python checkbox bokeh

以下代码生成带有复选框的散景图,可以使图形可见/不可见。它的效果很好,但是我想知道是否可以限制允许选中的复选框的数量,例如,现在不超过2个。

import numpy as np
from bokeh.io import output_file, show
from bokeh.layouts import row
from bokeh.palettes import Viridis3
from bokeh.plotting import figure
from bokeh.models import CheckboxGroup, CustomJS

output_file("line_on_off.html", title="line_on_off.py example")

p = figure()
props = dict(line_width=4, line_alpha=0.7)
x = np.linspace(0, 4 * np.pi, 100)
l0 = p.line(x, np.sin(x), color=Viridis3[0], legend="Line 0", **props)
l1 = p.line(x, 4 * np.cos(x), color=Viridis3[1], legend="Line 1", **props)
l2 = p.line(x, np.tan(x), color=Viridis3[2], legend="Line 2", **props)

checkbox = CheckboxGroup(labels=["Line 0", "Line 1", "Line 2"],
                         active=[0, 1, 2], width=100)
checkbox.callback = CustomJS.from_coffeescript(args=dict(l0=l0, l1=l1, l2=l2, checkbox=checkbox), code="""
l0.visible = 0 in checkbox.active;
l1.visible = 1 in checkbox.active;
l2.visible = 2 in checkbox.active;
""")

layout = row(checkbox, p)
show(layout)

我认为可以使用javascript完成此操作,但是我不知道如何访问此处涉及的javascript。我可以编写JavaScript并以某种方式将其与我的bokeh图集成吗? 我非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

# Store the current checkbox selection somewhere
current_checkbox_ticks = [0, 1]

# Your callback function
def checkbox_ticks(attr):
    # Go get the new selection
    new_ticks = checkbox.active
    if len(new_ticks) > 2:
        # If more than 2, set it to the previous selection
        checkbox.active = current_checkbox_ticks
    else:
        # If up to 2 now, update the stored variable
        current_checkbox_ticks = checkbox.active
    do_some_update()


# Set callback function
checkbox.on_click(checkbox_ticks)