实时显示数据对于数据采集,分析系统都是非常必要的。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)