Bokeh脚本运行中无法增量可视化图表问题求助
解决Bokeh脚本增量可视化问题
问题根源
你代码中的input("Continue...")会阻塞Bokeh服务器的主线程事件循环,导致服务器无法实时将图表更新推送到浏览器,必须等整个脚本执行完毕、所有阻塞解除后,才会一次性渲染所有内容。
解决方案:用Bokeh交互组件替代控制台输入
我们可以用Bokeh的Button组件实现手动触发下一步操作,既不会阻塞事件循环,又能满足分步可视化的需求。修改后的代码如下:
#!/usr/bin/python3 from bokeh.plotting import curdoc, figure from bokeh.models import Button from bokeh.layouts import column import numpy as np # 存储当前要更新的图表数据源 current_source = None # 定义步骤流程队列 steps = [] def plot_init(title): p = figure(title=title) plot_circle = p.circle([], []) curdoc().add_root(p) return plot_circle.data_source def step1(): global current_source # 初始化第一个图表并推送数据 current_source = plot_init("graph 1") temp_x = np.random.rand(10) temp_y = np.random.rand(10) current_source.stream({'x': temp_x, 'y': temp_y}) # 启用下一步按钮 next_button.disabled = False def step2(): global current_source # 初始化第二个图表并推送数据 current_source = plot_init("graph 2") temp_x = np.random.rand(10) temp_y = np.random.rand(10) current_source.stream({'x': temp_x, 'y': temp_y}) # 完成后禁用按钮 next_button.disabled = True def on_next_click(): if steps: # 执行当前步骤并从队列移除 steps.pop(0)() # 初始化步骤队列 steps.append(step1) steps.append(step2) # 创建「继续」按钮并绑定点击事件 next_button = Button(label="继续", disabled=True) next_button.on_click(on_next_click) curdoc().add_root(column(next_button)) # 启动第一步 on_next_click()
运行说明
- 用
bokeh serve bokeh-test.py启动服务器 - 打开浏览器对应URL,会自动显示第一个图表
- 点击页面上的「继续」按钮,即可生成并显示第二个图表
自动分步方案(无需手动触发)
如果不需要手动确认,仅需按顺序自动分步更新,可使用add_next_tick_callback避免阻塞:
#!/usr/bin/python3 from bokeh.plotting import curdoc, figure import numpy as np def plot_init(title): p = figure(title=title) plot_circle = p.circle([], []) curdoc().add_root(p) return plot_circle.data_source def step1(): # 初始化第一个图表并推送数据 source = plot_init("graph 1") temp_x = np.random.rand(10) temp_y = np.random.rand(10) source.stream({'x': temp_x, 'y': temp_y}) # 安排下一步执行 curdoc().add_next_tick_callback(step2) def step2(): # 初始化第二个图表并推送数据 source = plot_init("graph 2") temp_x = np.random.rand(10) temp_y = np.random.rand(10) source.stream({'x': temp_x, 'y': temp_y}) # 启动第一步 curdoc().add_next_tick_callback(step1)
该版本会自动依次生成两个图表,每一步完成后立即在浏览器中显示。
内容的提问来源于stack exchange,提问作者vicmortelmans
相关产品推荐
相关产品推荐

