具有MatplotlibAnimation的Arduino Live串行绘图速度变慢 [英] Arduino Live Serial Plotting with a MatplotlibAnimation gets slow

查看:140
本文介绍了具有MatplotlibAnimation的Arduino Live串行绘图速度变慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个实时绘图仪,以显示Arduino传感器的模拟变化. Arduino将波特率为9600的值打印到串行中.Python代码如下:

I am making a live plotter to show the analog changes from an Arduino Sensor. The Arduino prints a value to the serial with a Baudrate of 9600. The Python code looks as following:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
import time

ser = serial.Serial("com3", 9600)
ser.readline()

optimal_frequency = 100

fig = plt.figure(figsize=(6, 6))
ax1 = fig.add_subplot(1, 1, 1)

# the following arrays must be initialized outside the loop

xar = []
yar = []

print(time.ctime())

def animate(i):
    global b, xar, yar # otherwise a

    for i in range(optimal_frequency):

        a = str(ser.readline(), 'utf-8')
        try:
            b = float(a)
        except ValueError:
            ser.readline()
        xar.append(str(time.time()))
        yar.append(b)
    ax1.clear()
    ax1.plot(xar, yar)

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

在图中得到一个好的响应时间,但是当我绘制20分钟以上时,反应时间增加到大约1分钟. IE.该图需要1分钟才能用新值进行更新.我也尝试过使用PyQtGraph,但这从一开始就被延迟了.

A get an ok response time in the plot, but when I have been plotting over 20 minutes the reaction times increase to about 1 min. I.e. it takes 1 min forthe graph to get updated with the new values. I have also tried with PyQtGraph but that is delayed from a start.

除了延迟超过20分钟以外,我在图中还出现了一些过冲和下冲.

Besides the delay for times over 20 minutes, I am getting some overshoots and undershoots in the plot.

有帮助吗?

推荐答案

,您做错了两件事:

  • 您一直将传入的数据追加到数组中,一段时间后数组会变得庞大
  • 您清除轴并在每次迭代时创建一个新的ax.plot().

您要做的是:

在初始化函数中,创建一个空的Line2D对象

in an initialization function, create an empty Line2D object

def init():
    line, = ax.plot([], [], lw=2)
    return line,

然后在更新功能(animate())中,使用line.set_data()更新点的坐标.但是,为了保持性能,您必须将阵列的大小保持在合理的大小,因此,随着新数据的传入,您将不得不丢弃旧数据.

then in your update function (animate()), you use line.set_data() to update the coordinates of your points. However, to maintain performance, you have to keep the size of your arrays to a reasonable size, and so you will have to drop the older data as newer data comes in

def animate(i):
    (...)
    xar.append(str(time.time()))
    yar.append(b)
    line.set_data(xar, yar)
    return line,

查看一些教程像这样的.关于SO的问题也很多,已经回答了您的问题.例如,此答案包含使代码正常工作所需的所有元素.

Check out some tutorials like this one. There are also plenty of questions on SO that already answers your question. For instance, this answer contains all the elements you need to get your code working.

这篇关于具有MatplotlibAnimation的Arduino Live串行绘图速度变慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆