Python?Bokeh實現(xiàn)實時數(shù)據(jù)可視化
在數(shù)據(jù)分析和科學(xué)計算中,數(shù)據(jù)可視化是不可或缺的一部分。它能夠直觀地展示數(shù)據(jù),幫助我們快速發(fā)現(xiàn)規(guī)律和趨勢。Bokeh是Python中一個強(qiáng)大的數(shù)據(jù)可視化庫,尤其擅長創(chuàng)建交互式和實時更新的圖表。本文將通過簡潔的語言和具體的代碼示例,介紹如何使用Bokeh庫進(jìn)行實時數(shù)據(jù)可視化。
一、Bokeh簡介
Bokeh提供了豐富的圖表類型和工具,支持創(chuàng)建復(fù)雜的可視化作品,并可以輕松地嵌入到網(wǎng)頁中。它的核心特性包括:
- 交互式圖表:用戶可以與圖表進(jìn)行交互,如縮放、平移、懸停查看數(shù)據(jù)點信息等。
- 實時更新:Bokeh能夠?qū)崟r更新圖表,非常適合用于監(jiān)控和實時數(shù)據(jù)分析。
- 豐富的圖表類型:包括折線圖、柱狀圖、散點圖、熱力圖等。
- 易于集成:可以與Jupyter Notebook、Flask等框架無縫集成。
二、安裝 Bokeh
在開始之前,你需要確保已經(jīng)安裝了Bokeh庫。可以使用以下命令進(jìn)行安裝:
pip install bokeh
三、創(chuàng)建簡單的Bokeh圖表
讓我們從創(chuàng)建一個簡單的折線圖開始,了解Bokeh的基本用法。
from bokeh.plotting import figure, show, output_file from bokeh.io import output_notebook import numpy as np # 在Jupyter Notebook中顯示Bokeh圖表 output_notebook() # 創(chuàng)建數(shù)據(jù) x = np.linspace(0, 10, 100) y = np.sin(x) # 創(chuàng)建圖表對象 p = figure(title="Simple Line Plot", x_axis_label='x', y_axis_label='sin(x)') # 添加數(shù)據(jù)到圖表 p.line(x, y, line_width=2) # 顯示圖表 show(p)
這段代碼創(chuàng)建了一個簡單的折線圖,顯示了函數(shù)sin(x)在區(qū)間[0, 10]上的變化。在Jupyter Notebook中,output_notebook()函數(shù)允許直接在筆記本中顯示Bokeh圖表。
四、實時更新圖表
Bokeh的強(qiáng)大之處在于它能夠?qū)崟r更新圖表。這通常涉及到兩個主要部分:數(shù)據(jù)源的更新和圖表的重繪。
我們可以使用ColumnDataSource作為數(shù)據(jù)源,并通過回調(diào)函數(shù)在數(shù)據(jù)更新時觸發(fā)圖表的重新渲染。以下是一個簡單的示例,展示了如何創(chuàng)建一個實時更新的折線圖。
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource
from bokeh.layout import row
from bokeh.client import push_session
from bokeh.server.server import Server
import numpy as np
import time
import random
# 創(chuàng)建數(shù)據(jù)源
source = ColumnDataSource(data=dict(x=[], y=[]))
# 創(chuàng)建圖表對象
p = figure(title="Real-time Line Plot", x_axis_label='Time', y_axis_label='Value', x_range=(0, 50))
p.line('x', 'y', source=source, line_width=2)
# 更新數(shù)據(jù)的回調(diào)函數(shù)
def update():
new_data = {'x': source.data['x'] + [source.data['x'][-1] + 1 if source.data['x'] else 0],
'y': source.data['y'] + [random.uniform(0, 10)]}
source.stream(new_data, rollover=len(source.data['x']) > 50) # 保持最多50個數(shù)據(jù)點
# 設(shè)置回調(diào)函數(shù)定期調(diào)用
curdoc().add_periodic_callback(update, 1000) # 每1000毫秒(1秒)更新一次
# 如果在Jupyter Notebook中運行,則使用show()顯示圖表
# 否則,使用Bokeh服務(wù)器運行
# show(row(p), notebook_handle=True) # Jupyter Notebook方式
# 使用Bokeh服務(wù)器方式
session = push_session(curdoc())
try:
server = Server({'/': curdoc()}, io_loop=session.loop, allow_websocket_origin=["*"])
server.start()
session.loop_until_closed()
except KeyboardInterrupt:
pass
finally:
session.close()
server.stop()在這個示例中,我們創(chuàng)建了一個ColumnDataSource作為數(shù)據(jù)源,并通過update函數(shù)定期更新數(shù)據(jù)。stream方法用于向數(shù)據(jù)源添加新數(shù)據(jù),rollover參數(shù)確保數(shù)據(jù)源中的數(shù)據(jù)點數(shù)量不會超過50個。我們使用add_periodic_callback方法設(shè)置回調(diào)函數(shù)每1000毫秒(1秒)調(diào)用一次。
注意:如果你在Jupyter Notebook中運行這段代碼,你可能需要使用show(row(p), notebook_handle=True)來顯示圖表。然而,對于實時更新,更常見的方式是使用Bokeh服務(wù)器。上面的代碼示例展示了如何使用Bokeh服務(wù)器運行圖表,并通過push_session和Server類進(jìn)行配置。
五、集成到Flask應(yīng)用中
Bokeh還可以與Flask等Web框架集成,創(chuàng)建完整的Web應(yīng)用。以下是一個簡單的示例,展示了如何將Bokeh圖表集成到Flask應(yīng)用中。
from flask import Flask, render_template_string
from bokeh.plotting import figure
from bokeh.embed import components
from bokeh.resources import CDN
from bokeh.models import ColumnDataSource
import numpy as np
app = Flask(__name__)
# 創(chuàng)建Bokeh圖表和數(shù)據(jù)源
source = ColumnDataSource(data=dict(x=np.linspace(0, 10, 100), y=np.sin(np.linspace(0, 10, 100))))
p = figure(title="Flask-integrated Bokeh Plot", x_axis_label='x', y_axis_label='sin(x)')
p.line('x', 'y', source=source, line_width=2)
# 將Bokeh圖表嵌入到HTML模板中
script, div = components(p, CDN)
# 定義Flask路由和視圖函數(shù)
@app.route('/')
def index():
html = render_template_string("""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flask-integrated Bokeh Plot</title>
{{ script|safe }}
</head>
<body>
{{ div|safe }}
</body>
</html>
""", script=script, div=div)
return html
if __name__ == '__main__':
app.run(debug=True)在這個示例中,我們首先創(chuàng)建了一個簡單的Bokeh圖表和數(shù)據(jù)源。然后,我們使用components函數(shù)將圖表轉(zhuǎn)換為HTML腳本和div元素。接著,我們定義了一個Flask路由和視圖函數(shù),將Bokeh圖表嵌入到HTML模板中并返回給客戶端。
運行這個Flask應(yīng)用后,你可以在瀏覽器中打開http://127.0.0.1:5000/查看嵌入的Bokeh圖表。
六、注意事項
性能優(yōu)化:對于大量數(shù)據(jù)的實時更新,可能需要考慮性能優(yōu)化,如減少數(shù)據(jù)源中的數(shù)據(jù)點數(shù)量、使用更高效的數(shù)據(jù)結(jié)構(gòu)等。
安全性:在將Bokeh圖表集成到Web應(yīng)用中時,務(wù)必注意安全性問題,如防止跨站腳本攻擊(XSS)等。
錯誤處理:在實時數(shù)據(jù)更新過程中,可能會遇到各種異常情況(如網(wǎng)絡(luò)中斷、數(shù)據(jù)源異常等),需要做好錯誤處理。
七、總結(jié)
本文介紹了如何使用Python的Bokeh庫進(jìn)行實時數(shù)據(jù)可視化。我們從一個簡單的折線圖開始,逐步深入了解了如何實時更新圖表、如何將圖表集成到Flask應(yīng)用中等高級用法。
以上就是Python Bokeh實現(xiàn)實時數(shù)據(jù)可視化的詳細(xì)內(nèi)容,更多關(guān)于Python Bokeh數(shù)據(jù)可視化的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
django之從html頁面表單獲取輸入的數(shù)據(jù)實例
這篇文章主要介紹了django之從html頁面表單獲取輸入的數(shù)據(jù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python使用selenium實現(xiàn)批量文件下載
這篇文章主要介紹了python使用selenium實現(xiàn)批量文件下載,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
Python+OpenCV開發(fā)中的常見錯誤及解決方案
本文總結(jié)了OpenCV使用中的常見錯誤及解決方案,幫助開發(fā)者快速定位和解決計算機(jī)視覺開發(fā)中的問題,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2026-05-05
高考要來啦!用Python爬取歷年高考數(shù)據(jù)并分析
轉(zhuǎn)眼間,高考的日子又要來臨了,不知道高考學(xué)子們準(zhǔn)備的怎么樣了,今天這篇文章簡單且隨意地分析一下高考的一些數(shù)據(jù),需要的朋友可以參考下2021-06-06
pytorch中的named_parameters()和parameters()
這篇文章主要介紹了pytorch中的named_parameters()和parameters()使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09

