以下是一个使用Bokeh的示例代码,展示了如何使用PATCH-DOC和ping-pong模式来重置绘图:
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource
from bokeh.layouts import column
from bokeh.io import show
import time
# 创建一个空的数据源
source = ColumnDataSource(data=dict(x=[], y=[]))
# 创建绘图对象
p = figure(plot_width=400, plot_height=400)
p.circle(x='x', y='y', source=source)
# 创建一个按钮,并定义回调函数
button = Button(label="Reset")
def reset_plot():
# 清空数据源
source.data = dict(x=[], y=[])
# 更新绘图
source.change.emit()
button.on_click(reset_plot)
# 将按钮和绘图放在一起
layout = column(button, p)
# 创建文档并添加布局
doc = curdoc()
doc.add_root(layout)
# 定义ping-pong模式的回调函数
def update():
while True:
# 添加新的数据点到数据源
new_data = dict(x=[1, 2, 3], y=[4, 5, 6])
source.stream(new_data, rollover=10)
# 更新绘图
source.change.emit()
# 暂停一秒钟
time.sleep(1)
# 启动ping-pong模式的回调函数
doc.add_periodic_callback(update, 2000)
# 在终端中运行此脚本,并在浏览器中打开Bokeh应用程序
show(layout)
这个示例代码创建了一个带有重置按钮的散点图。当单击按钮时,数据源将被重置为空,并清空绘图。然后,使用ping-pong模式定期向数据源添加新数据点,并更新绘图。