我正在尝试在Matplotlib实时图表上显示来自传感器的数据。
我想创建一个连续读取传感器的线程。然后我使用matplotlib.animation
来更新当时传感器读数列表中的任何数据。
问题是matplotlib.animation
似乎只从传感器读取数据一次,然后冻结。关于如何解决这个问题的任何想法?
import random
import threading
import matplotlib.animation as animation
import matplotlib.pyplot as plt
def ReadSensors():
global listXData
global listTemp
# Should be sensor data. Using dummy random data for now...
listTemp = [ random.randint(0,5) for x in listXData ]
def UpdateFigure(oFrame):
global listXData
oCurve_Temp.set_data(listXData, listTemp)
return oCurve_Temp,
# Initialize data lists
listXData = range(0,100)
listTemp = [0 for x in listXData]
# Initialize graph
fig, ax = plt.subplots()
ax.set_title('Temperature')
ax.set_xlabel('Data Point')
ax.set_ylabel('[oC]')
ax.set_xlim( 0, 100)
ax.set_ylim( 0, 5)
oCurve_Temp, = ax.plot([],[])
# Starts reading sensor
oThread_ReadSensors = threading.Thread(target = ReadSensors)
oThread_ReadSensors.daemon = True
oThread_ReadSensors.start()
# Update graph
ani = animation.FuncAnimation(fig, UpdateFigure, interval=500)
plt.show()
答案 0 :(得分:1)
您没有看到任何动画,因为数据实际上并未发生变化。因此动画再次显示所有相同的数据。 实际更改数据是有意义的。 数据下方每600毫秒更改一次,动画每400毫秒显示一个新帧,因此某些帧显示与前一帧相同的数据。
import time
import random
import threading
import matplotlib.animation as animation
import matplotlib.pyplot as plt
def ReadSensors():
global listXData
global listTemp
# Should be sensor data. Using dummy random data for now...
while True:
listTemp = [ random.randint(0,5) for x in listXData ]
time.sleep(0.6)
def UpdateFigure(oFrame):
print "update"
global listXData
oCurve_Temp.set_data(listXData, listTemp)
return oCurve_Temp,
# Initialize data lists
listXData = range(0,100)
listTemp = [0 for x in listXData]
# Initialize graph
fig, ax = plt.subplots()
ax.set_title('Temperature')
ax.set_xlabel('Data Point')
ax.set_ylabel('[oC]')
ax.set_xlim( 0, 100)
ax.set_ylim( 0, 5)
oCurve_Temp, = ax.plot([],[])
# Starts reading sensor
oThread_ReadSensors = threading.Thread(target = ReadSensors)
oThread_ReadSensors.daemon = True
oThread_ReadSensors.start()
# Update graph
ani = animation.FuncAnimation(fig, UpdateFigure, interval=400)
plt.show()
# Join the thread not to run into
# an unterminated threat when closing the figure
oThread_ReadSensors.join()