以下是使用 Select 组件和 CustomJS 更新图表的 Bokeh 代码示例:
from bokeh.io import output_file, show
from bokeh.layouts import row, column
from bokeh.models import Select, CustomJS
from bokeh.plotting import figure
from bokeh.sampledata.iris import flowers
# 创建一个包含所有不同种类的列表
species = flowers['species'].unique().tolist()
# 创建一个 Select 组件
select = Select(title="Species", options=species)
# 创建一个空的图表
p = figure(width=400, height=400)
# 创建一个自定义回调函数
callback = CustomJS(args=dict(source=select, plot=p), code="""
// 获取 Select 组件当前的值
var species = source.value;
// 根据选择的值过滤数据
var new_data = data[data['species'] == species];
// 更新图表的数据
plot.data_source.data = new_data;
plot.change.emit();
""")
# 将回调函数绑定到 Select 组件的值变化事件上
select.js_on_change('value', callback)
# 初始化图表的数据
data = flowers[flowers['species'] == species[0]]
# 绘制散点图
p.circle(x='petal_length', y='petal_width', source=data, size=10)
# 将 Select 组件和图表放在一起显示
layout = row(column(select), p)
# 输出到 HTML 文件并显示
output_file("bokeh_select_example.html")
show(layout)
运行此代码将生成一个包含 Select 组件和散点图的 HTML 文件,并且当选择不同的物种时,图表将根据选择的物种更新数据。