使用动画函数在Matplotlib的Python中使用动画函数缓慢绘制



我需要您的帮助,因为这些天我要处理的问题。我可以绘制从我的手机蓝牙传输并由笔记本电脑端口接收的序列数据。乍一看似乎还可以,但最多可以每260毫秒(〜3 fps)绘制一次。但是,手机每100毫秒每100毫秒发送数据。我很确定问题源于使我感到困惑的"情节"one_answers"图"命令。如果有人能纠正我的代码:

我很感激
from Tkinter import *
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ser = serial.Serial("COM4", baudrate=115200, timeout=0.1)
cnt=0
xComponent=[]
plt.ylim(0,30)
while (ser.inWaiting() == 0): # Wait here until there is data
    pass
def animate(i):
    BluetoothString = ser.readline()
    ser.flush()
    dataArray = BluetoothString.split(',')
    x = float(dataArray[2]) # we only need 3rd component
    xComponent.append(x)
    print xComponent
    ax1.clear()
    ax1.plot(xComponent)
    plt.ylim(0,25)
    global cnt
    if (cnt > 16): 
        xComponent.pop(0)
    else:
        cnt = cnt + 1
ani = animation.FuncAnimation(fig, animate, interval=0)
plt.show()

关于您的特殊情况很难说任何内容,因为我们没有您使用的串行连接部分。

但是,如果这只是其中一些点的线图,则绘图应比Matplotlib中的3 fps快得多。一件事,您可以直接尝试它不要在每个迭代步骤中重新启动所有内容,而是一次绘制它,然后仅使用.set_data() 更新数据

以下示例与您的代码密切相关,并且在我的计算机上使用90 fps运行。因此,也许您尝试了一个,看看它是否有助于加速您的案件。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
cnt=0
xComponent=[]
line,  = ax1.plot([0], [0])
text = ax1.text(0.97,0.97, "", transform=ax1.transAxes, ha="right", va="top")
plt.ylim(0,25)
plt.xlim(0,100)
last_time = {0: time.time()}
def animate(i):
    if len(xComponent)>100:
        xComponent.pop(0)
    y = i % 25
    xComponent.append(y)
    line.set_data(range( len(xComponent) ) ,xComponent)
    new_time = time.time()
    text.set_text("{0:.2f} fps".format(1./(new_time-last_time[0])))
    last_time.update({0:new_time})

ani = animation.FuncAnimation(fig, animate, interval=0)
plt.show()

我不想在这里踩到任何脚趾,因为@importanceofbeingofenest钉上了它,但是在他的示例中添加闪烁使我的帧率从50到300。示例:我留下了我进行更改的评论

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
cnt=0
xComponent=[]
line,  = ax1.plot([0], [0])
text = ax1.text(0.97,0.97, "", transform=ax1.transAxes, ha="right", va="top")
plt.ylim(0,25)
plt.xlim(0,100)
last_time = {0: time.time()}
def animateinit(): #tells our animator what artists will need re-drawing every time
    return line,text
def animate(i):
    if len(xComponent)>100:
        xComponent.pop(0)
    y = i % 25
    xComponent.append(y)
    line.set_data(range( len(xComponent) ) ,xComponent)
    new_time = time.time()
    text.set_text("{0:.2f} fps".format(1./(new_time-last_time[0])))
    last_time.update({0:new_time})
    return line,text #return the updated artists
#inform the animator what our init_func is and enable blitting
ani = animation.FuncAnimation(fig, animate, interval=0,init_func=animateinit, blit=True) 
plt.show()

MPL中的每个绘制呼叫都相当昂贵,因此,如果我们能尽可能少地绘制,我们会看到巨大的加速。通过告诉动画师仅重新绘制某些元素,我们避免了重新绘制轴标记,轴标签,计算缩放等的内容。这些东西看起来很简单,但是有很多,而开销很快就加起来了。

最新更新