如何在Bokeh回调中通过RadioButtonGroup切换pandas read_excel文件?
因为你对JS不熟悉,优先推荐服务器端回调方案,全程用Python实现,不用写CustomJS,操作更简单。
服务器端回调实现步骤
- 初始化Bokeh文档,加载默认数据源(比如默认选中的
a.xlsx) - 创建RadioButtonGroup控件,绑定回调函数
- 在回调函数中根据选中的按钮索引,切换读取对应的Excel文件,更新图表数据源
完整代码示例
from bokeh.plotting import figure, curdoc from bokeh.models import ColumnDataSource, RadioButtonGroup from bokeh.layouts import column import pandas as pd # 定义数据源前缀列表 graphs = ['a', 'b'] # 封装读取Excel并转换为数据源的逻辑 def load_data(file_prefix): df = pd.read_excel(f"{file_prefix}.xlsx") # 请根据你的Excel实际列名修改x、y字段 return ColumnDataSource(data=dict(x=df['x'], y=df['y'])) # 加载初始数据(默认选中第一个按钮) source = load_data(graphs[0]) # 创建折线图 p = figure(title="切换Excel数据源示例", x_axis_label='X轴', y_axis_label='Y轴') p.line('x', 'y', source=source, line_width=2) # 创建单选按钮组 button_group = RadioButtonGroup(labels=graphs, active=0) # 定义切换数据源的回调函数 def update_data(attr, old, new): # new是选中按钮的索引,对应graphs里的文件名前缀 selected_prefix = graphs[new] new_source = load_data(selected_prefix) # 更新数据源,图表会自动刷新 source.data = new_source.data # 绑定回调到单选按钮的active属性变化 button_group.on_change('active', update_data) # 布局并添加到Bokeh文档 layout = column(button_group, p) curdoc().add_root(layout)
运行说明
执行命令启动Bokeh服务器即可运行:
bokeh serve --show your_script.py
如果需要静态部署(不需要启动Bokeh服务器),可以用前端CustomJS方案,但需要提前加载所有Excel数据,适合数据量不大的场景:
前端CustomJS方案示例
from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource, RadioButtonGroup, CustomJS from bokeh.layouts import column import pandas as pd # 提前加载所有Excel数据 data_a = pd.read_excel('a.xlsx') data_b = pd.read_excel('b.xlsx') # 把所有数据存入字典,供JS调用 all_data = { 'a': dict(x=data_a['x'], y=data_a['y']), 'b': dict(x=data_b['x'], y=data_b['y']) } # 初始化数据源 source = ColumnDataSource(data=all_data['a']) # 创建折线图 p = figure(title="前端切换数据源示例", x_axis_label='X轴', y_axis_label='Y轴') p.line('x', 'y', source=source, line_width=2) # 创建单选按钮组 button_group = RadioButtonGroup(labels=['a', 'b'], active=0) # 编写CustomJS回调逻辑 callback = CustomJS(args=dict(source=source, all_data=all_data), code=""" const selected = cb_obj.labels[cb_obj.active]; source.data = all_data[selected]; source.change.emit(); """) # 绑定回调到单选按钮 button_group.js_on_change('active', callback) # 布局并显示 layout = column(button_group, p) show(layout)
内容的提问来源于stack exchange,提问作者CodingNoob
相关产品推荐
相关产品推荐

