使用ColumnDataSource()和Bokeh创建交互式图表应用的步骤
发布时间:2023-12-18 16:33:28
使用ColumnDataSource()和Bokeh创建交互式图表应用的步骤如下:
1. 导入必要的库和模块:
from bokeh.plotting import figure, curdoc from bokeh.models import ColumnDataSource from bokeh.layouts import row
2. 创建数据源:
source = ColumnDataSource(data=dict(x=[], y=[]))
3. 创建绘图对象:
p = figure(plot_width=400, plot_height=400)
4. 创建绘图元素:
circle = p.circle('x', 'y', size=10, fill_color='blue', line_color='black', source=source)
5. 创建回调函数:
def update_data():
new_data = dict(x=[1, 2, 3, 4, 5], y=[1, 4, 9, 16, 25])
source.data = new_data
6. 创建交互控件:
button = Button(label="Update Data") button.on_click(update_data)
7. 创建布局:
layout = row(p, button)
8. 添加布局到文档:
curdoc().add_root(layout)
9. 运行应用:
bokeh serve --show myapp.py
下面是一个完整的例子:
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource
from bokeh.layouts import row
from bokeh.models.widgets import Button
source = ColumnDataSource(data=dict(x=[], y=[]))
p = figure(plot_width=400, plot_height=400)
circle = p.circle('x', 'y', size=10, fill_color='blue', line_color='black', source=source)
def update_data():
new_data = dict(x=[1, 2, 3, 4, 5], y=[1, 4, 9, 16, 25])
source.data = new_data
button = Button(label="Update Data")
button.on_click(update_data)
layout = row(p, button)
curdoc().add_root(layout)
运行以上代码,将会生成一个包含一个点和一个按钮的交互式图表应用。当点击按钮时,图表中的点将会更新为新的数据。
