希望按照 UI 的方式做一些事情,如下所示:Bokeh:使用复选框小部件隐藏和显示绘图,其中我可以有选择地显示/隐藏一列数字中的整个数字。最好有一个下拉菜单(带有多个选择的选项菜单),我可以在其中选择显示哪些图(假设我可以命名这些图)。
我对JS不熟悉,有什么指导吗? (提前谢谢)
我希望图像不再可见,下一个数字会像这样跳起来:
我在一列中有多个数字,生成为:
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.plotting import figure
output_file("layout.html")
x = list(range(11))
y0 = x
y1 = [10 - i for i in x]
y2 = [abs(i - 5) for i in x]
# create a new plot
s1 = figure(plot_width=250, plot_height=250, title=None)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)
# create another one
s2 = figure(plot_width=250, plot_height=250, title=None)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)
# create and another
s3 = figure(plot_width=250, plot_height=250, title=None)
s3.square(x, y2, size=10, color="olive", alpha=0.5)
# put the results in a column and show
show(column(s1, s2, s3))
原来的答案已经过时了。散景图对象(例如来自
figure
)具有 visible
属性(并且已经有一段时间了),可以通过 CustomJS
核心或 Python 代码来打开或关闭该属性。
已过时
绘图没有
visible
切换,至少从版本 0.13 开始。因此,您必须重置布局小部件的 children
值。我不太确定您想要与下拉菜单进行什么交互。这是带有复选框的完整示例:
from bokeh.io import output_file, show
from bokeh.layouts import column, row
from bokeh.plotting import figure
from bokeh.models import CheckboxGroup, CustomJS
output_file("layout.html")
x = list(range(11))
y0 = x
y1 = [10 - i for i in x]
y2 = [abs(i - 5) for i in x]
s1 = figure(plot_width=250, plot_height=250, title=None)
s1.circle(x, y0, size=10, color="navy", alpha=0.5)
s2 = figure(plot_width=250, plot_height=250, title=None)
s2.triangle(x, y1, size=10, color="firebrick", alpha=0.5)
s3 = figure(plot_width=250, plot_height=250, title=None)
s3.square(x, y2, size=10, color="olive", alpha=0.5)
col = column(s1, s2, s3)
checkbox = CheckboxGroup(labels=["Plot 1", "Plot 2", "Plot 3"],
active=[0, 1, 2], width=100)
callback = CustomJS(args=dict(plots=[s1,s2, s3], col=col, checkbox=checkbox), code="""
const children = []
for (const i of checkbox.active) {
children.push(plots[i])
}
col.children = children
""")
checkbox.js_on_change('active', callback)
show(row(checkbox, col))
你可以用
MultiSelect
做类似的事情:
select = MultiSelect(options=[("0", "Plot 1"), ("1", "Plot 2"), ("2", "Plot 3")],
value=["0", "1", "2"], width=100)
callback = CustomJS(args=dict(plots=[s1,s2, s3], col=col, select=select), code="""
const children = []
for (const i of select.value) {
children.push(plots[i])
}
col.children = children
""")
select.js_on_change('value', callback)
仅供参考,该代码有点草率 - 它依赖于 JS 隐式将“0”等字符串转换为数字。
s1.tags, s2.tags, s3.tags = ['Foo'], ['Bar'], ['Arr'] # name your plots
plots = [s1, s2, s3]
labels = [(plots[i].tags[0]) for i in range(len(plots))]
active = list(range(0, len(plots)))
chkbx = CheckboxButtonGroup(labels=labels, active=active)
callback = CustomJS(args=dict(plots=plots, chkbx=chkbx), code="""
for (let i = 0; i < plots.length; i++){
plots[i].visible = chkbx.active.includes(i)
}
""")
chkbx.js_on_click(callback)
show(column([chkbx] + plots))
感谢@bigreddot 和他们的answer 为这个解决方案奠定了基础。