如何获取Bokeh滑块(w,A,Phi)修改后的实际值?求示例代码
获取Bokeh滑块实时值的Jupyter Notebook示例代码
针对你提到的Bokeh Jupyter交互示例,要获取滑块w、A、Phi的实时值,直接利用ipywidgets的监听机制就能实现,不需要复杂的Bokeh回调。以下是修改后的完整代码,滑块调整时会实时输出当前值,你也可以根据需求把值保存到变量或用于其他逻辑:
import numpy as np from bokeh.plotting import figure, show from bokeh.io import push_notebook, output_notebook from ipywidgets import interact # 初始化Jupyter Notebook的Bokeh输出环境 output_notebook() # 生成初始数据 x = np.linspace(0, 2*np.pi, 200) w = 1.0 A = 1.0 Phi = 0.0 y = A * np.sin(w * x + Phi) # 创建绘图对象 p = figure(title="Interactive Sine Wave", plot_height=300, plot_width=600) r = p.line(x, y, color="#2222aa", line_width=3) # 显示绘图并保留句柄用于后续更新 target = show(p, notebook_handle=True) # 定义更新函数,同步获取滑块实时值 def update(w=1.0, A=1.0, Phi=0.0): # 保存当前滑块值到变量(可按需用于其他逻辑) current_w = w current_A = A current_Phi = Phi # 打印实时值,可替换为写入文件、存储到全局变量等操作 print(f"当前滑块值:w={current_w:.2f}, A={current_A:.2f}, Phi={current_Phi:.2f}") # 更新绘图数据并推送至Notebook y = A * np.sin(w * x + Phi) r.data_source.data['y'] = y push_notebook(handle=target) # 创建交互控件并绑定更新函数 interact(update, w=(0.1, 5.0), A=(0.1, 2.0), Phi=(-np.pi, np.pi))
补充说明:
- 若希望滑块调整结束后才触发值获取(而非拖动过程中实时触发),可以给
interact添加参数:interact(update, w=(0.1, 5.0), A=(0.1, 2.0), Phi=(-np.pi, np.pi), continuous_update=False) - 你可以移除
print语句,将滑块值存储到全局变量或直接用于数据计算、结果导出等业务场景。
内容的提问来源于stack exchange,提问作者polgia0
相关产品推荐
相关产品推荐

