Bokeh 是一个 Python 交互式可视化库,它允许用户创建复杂的图形和数据应用程序。CustomJS 是 Bokeh 中的一个 JavaScript 回调,可以在用户界面上执行自定义的 JavaScript 代码。当与 CheckboxGroup
结合使用时,CustomJS 可以用来动态更新散点图的数据源,从而实现过滤功能。
以下是一个简单的示例,展示了如何使用 CustomJS 从 CheckboxGroup
更新散点图的数据源:
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.models import CheckboxGroup, ColumnDataSource
from bokeh.plotting import figure
# 准备数据
data = {'x': [1, 2, 3, 4, 5], 'y': [6, 7, 2, 4, 5], 'labels': ['A', 'B', 'C', 'D', 'E']}
source = ColumnDataSource(data)
# 创建散点图
p = figure(plot_width=400, plot_height=400)
scatter = p.circle('x', 'y', source=source, size=20)
# 创建 CheckboxGroup
checkbox_group = CheckboxGroup(labels=data['labels'], active=[0, 1, 2])
# 定义 CustomJS 回调
callback = CustomJS(args=dict(source=source, checkbox_group=checkbox_group), code="""
const data = source.data;
const active = checkbox_group.active;
const labels = checkbox_group.labels;
const x = data['x'];
const y = data['y'];
for (let i = 0; i < labels.length; i++) {
x[i] = active.includes(i) ? data['x'][i] : null;
y[i] = active.includes(i) ? data['y'][i] : null;
}
source.change.emit();
""")
# 将回调绑定到 CheckboxGroup
checkbox_group.js_on_change('active', callback)
# 布局并显示
layout = column(checkbox_group, p)
output_file("filter.html")
show(layout)
问题: 当用户选择或取消选择 CheckboxGroup
中的选项时,散点图没有更新。
原因: 可能是因为回调函数没有正确地绑定到 CheckboxGroup
的 active
属性变化事件上。
解决方法: 确保使用 js_on_change
方法将回调函数绑定到正确的属性上,并且在回调函数中正确地修改了数据源。
通过上述代码示例和解释,你应该能够理解如何使用 Bokeh 和 CustomJS 来创建一个交互式的散点图过滤功能。如果遇到具体的技术问题,可以根据错误信息进行调试,或者查阅 Bokeh 的官方文档获取更多帮助。
领取专属 10元无门槛券
手把手带您无忧上云