matplotlib在多线程中运行时不稳定



我正在处理一个问题,即从dll中获取数据以使用matplotlib绘制实时图。该过程运行良好,能够生成实时图形。我使用多线程来获得高频率的数据,并以较慢的速率绘制。这是因为我需要一个2000Hz的数据集,同时能够实时显示。

但是,当用于获取数据的其他函数运行良好时,该图将停止运行约15秒。

import sys
import ctypes as ct
import time
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from matplotlib.animation import FuncAnimation
import threading
mod_name = r"G:softwaredataliteOnLineInterface.dll"
# mod_name = "kernel32"
OnLineInterfaceDll = ct.WinDLL(mod_name)
OnLineStatus = OnLineInterfaceDll.OnLineStatus
OnLineStatus.argtypes = (ct.c_long, ct.c_long, ct.POINTER(ct.c_long))
a = ct.c_long(0)
b = ct.c_long(2)
c = ct.c_long()
OnLineStatus(a, b, ct.pointer(c))
xcache = []
ycache = []
def GetData():
i = 0
b = ct.c_long(1)
v = 0

b = ct.c_long(4)
while i < 5000000 :
OnLineStatus(a, b, ct.pointer(c))
cconv = ((c.value - 4000) / 1000)
print(cconv)
v = time.perf_counter()
print("time:", v)
xcache.append(v)
ycache.append(cconv)
i += 1
def DrawData():
figure, ax = plt.subplots(figsize=(8, 6))
plt.title("EMG signal", fontsize=25)
plt.xlabel("time(seconds", fontsize=18)
plt.ylabel("EMG(mV)", fontsize=18)

def animate(i):
plt.cla()
plt.plot(xcache, ycache)
print(xcache)

ani = FuncAnimation(plt.gcf(), animate, 1000)
plt.show()
if __name__ == "__main__":
t1 = threading.Thread(target=GetData)
t2 = threading.Thread(target=DrawData)
t1.start()
t2.start()
t1.join()
t2.join()

更新:当我将matplotlib每次显示的最大数组大小划分为20000时,实时数据运行稳定。

最新更新