實時顯示數據對於數據採集,分析系統都是非常必要的。Python作爲一種非常常用的語言,能夠在各種不同平臺上方便的使用。
在這個例子中,使用簡單的基礎函數實現數據的實時顯示。完整代碼下載請見:Python實時顯示數據。
1. 實時顯示函數live_plotter
def live_plotter(x_vec,y_vec_data,line_realtime,identifier='',pause_time=0.1):
if line_realtime==[]:
# this is the call to matplotlib that allows dynamic plotting
plt.ion()
fig = plt.figure(figsize=(13,6))
ax = fig.add_subplot(111)
# create a variable for the line so we can later update it
line_realtime, = ax.plot(x_vec,y_vec_data,'-o',alpha=0.8)
#update plot label/title
plt.ylabel('Y Label')
plt.title('Title: {}'.format(identifier))
plt.show()
# after the figure, axis, and line are created, we only need to update the y-data
line_realtime.set_xdata(x_vec)
line_realtime.set_ydata(y_vec_data)
# line_realtime.set_data(x_vec,y_vec_data)
# adjust limits if new data goes beyond bounds
if np.min(y_vec_data)<=line_realtime.axes.get_ylim()[0] or np.max(y_vec_data)>=line_realtime.axes.get_ylim()[1]:
plt.ylim([np.min(y_vec_data)-np.std(y_vec_data),np.max(y_vec_data)+np.std(y_vec_data)])
# this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
plt.pause(pause_time)
# return line so we can update it again in the next iteration
return line_realtime
這裏需要特別說明是,使用matplotlib顯示數據的方式和平時是一樣的,不同之處在於,接收到數據時,採用一下方式更新:
line_realtime.set_xdata(x_vec) #設置x軸數據
line_realtime.set_ydata(y_vec_data) #設置y軸數據
ine_realtime.set_data(x_vec,y_vec_data) #設置xy 軸數據
plt.pause()
是設置顯示的時間間隔,可以更改。
2. 調用數據顯示函數
更新x,y軸的數據x_vec,y_vec,實現數據顯示的更新。
def main():
print(__file__ + " start...")
size = 100
x_vec = np.linspace(0,1,size+1)[0:-1]
y_vec = np.random.randn(len(x_vec))
line_realtime = []
while True:
rand_val = np.random.randn(1)
y_vec[-1] = rand_val
line_realtime = live_plotter(x_vec,y_vec,line_realtime)
y_vec = np.append(y_vec[1:],0.0)