Bokeh 实时绘图 Bokeh Python 在不使用服务器的情况下
在本文中,我们将介绍如何使用Bokeh进行实时绘图,以及如何在不使用服务器的情况下将其集成到Python Flask中。
阅读更多:Bokeh 教程
什么是Bokeh?
Bokeh是一个Python库,用于创建交互式和动态的数据可视化。它支持多种绘图类型,包括折线图、散点图、柱状图等,使我们能够以美观的方式展示数据。
实时绘图
要在Bokeh中进行实时绘图,我们需要使用Bokeh的bokeh.models.ColumnDataSource和bokeh.models.Column来更新数据源。我们可以通过定期更新数据源来实现实时绘图。
下面是一个示例,展示了如何在Bokeh中实现每秒钟更新一次的实时折线图:
from bokeh.plotting import figure, curdoc
from bokeh.models.sources import ColumnDataSource
from random import randrange
from threading import Thread
from time import sleep
source = ColumnDataSource(data={'x': [], 'y': []})
p = figure(title='Realtime Plot', x_axis_label='X', y_axis_label='Y')
line = p.line(x='x', y='y', source=source)
def update_data():
    while True:
        new_data = {'x': [source.data['x'][-1]+1], 'y': [randrange(1, 10)]}
        source.stream(new_data,rollover=20)
        sleep(1)
update_thread = Thread(target=update_data)
update_thread.daemon = True
update_thread.start()
curdoc().add_root(p)
在这个示例中,我们首先创建了一个空的数据源source,其中包含x和y两列。然后,我们创建了一个折线图,并将数据源指定为我们刚刚创建的source。接下来,我们定义了一个update_data函数,它在其中通过生成随机数据并使用source.stream()将新数据追加到数据源中。然后,我们使用Thread和sleep函数以每秒钟更新一次的频率来调用update_data函数。最后,我们使用curdoc().add_root()将绘图添加到当前文档。
Bokeh与Python Flask集成
要在Python Flask中集成Bokeh,我们需要使用bokeh.embed模块的json_item函数来将Bokeh绘图转换为JSON格式,并将其嵌入到Flask模板中。
下面是一个示例,展示了如何在Python Flask中集成实时绘图的Bokeh应用:
from flask import Flask, render_template
from bokeh.plotting import figure
from bokeh.models.sources import ColumnDataSource
from bokeh.embed import json_item
from random import randrange
from threading import Thread
from time import sleep
app = Flask(__name__)
@app.route('/')
def index():
    source = ColumnDataSource(data={'x': [], 'y': []})
    p = figure(title='Realtime Plot', x_axis_label='X', y_axis_label='Y')
    line = p.line(x='x', y='y', source=source)
    def update_data():
        while True:
            new_data = {'x': [source.data['x'][-1]+1], 'y': [randrange(1, 10)]}
            source.stream(new_data, rollover=20)
            sleep(1)
    update_thread = Thread(target=update_data)
    update_thread.daemon = True
    update_thread.start()
    plot_json = json_item(p)
    return render_template('index.html', plot_json=plot_json)
if __name__ == '__main__':
    app.run(debug=True)
在这个示例中,我们首先创建了一个简单的Flask应用,并定义了一个路由/。在该路由函数中,我们创建了与之前相同的数据源source和折线图p。然后,我们使用Thread和sleep函数调用update_data函数,以每秒钟更新一次的频率更新数据源。最后,我们使用json_item函数将Bokeh绘图转换为JSON,并将其传递给Flask模板index.html来渲染页面。
总结
通过Bokeh和Python Flask的集成,我们可以实现实时的数据可视化。使用Bokeh的ColumnDataSource和Column类可以方便地更新数据源,从而实现实时绘图。而通过使用json_item函数,我们能够将Bokeh绘图转换为JSON并将其嵌入到Python Flask中。
无论是在科学研究中实时监测数据,还是在业务中实时呈现数据变化,Bokeh的实时绘图功能都能够为我们带来很大的方便和效果。通过集成到Python Flask中,我们可以更加灵活地展示和共享实时数据的可视化结果。
极客教程