Arduino Live Serial Plotting with a MatplotlibAnimation gets slow

2024/9/20 8:44:01

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 timeser = serial.Serial("com3", 9600)
ser.readline()optimal_frequency = 100fig = plt.figure(figsize=(6, 6))
ax1 = fig.add_subplot(1, 1, 1)# the following arrays must be initialized outside the loopxar = []
yar = []print(time.ctime())def animate(i):global b, xar, yar # otherwise afor 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()

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.

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

Any help?

Answer

as mentioned in the comments, you are doing two things wrong:

  • you keep appending incoming data to your arrays, which get huge after a while
  • you clear your axes and create a new ax.plot() at every iteration.

what you want to do instead is:

in an initialization function, create an empty Line2D object

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

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,

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.

https://en.xdnf.cn/q/119389.html

Related Q&A

Hide lines on tree view - openerp 7

I want to hide all lines (not only there cointaner) in sequence tree view (the default view). I must hide all lines if code != foo but the attrs atribute dont work on tree views, so how can i filter/hi…

Python Append dataframe generated in nested loops

My program has two for loops. I generate a df in each looping. I want to append this result. For each iteration of inner loop, 1 row and 24 columns data is generated. For each iteration of outer loop, …

bError could not find or load main class caused by java.lang.classnotfoundation error

I am trying to read the executable jar file using python. That jar file doesnt have any java files. It contains only class and JSON files. So what I tried is from subprocess import Popen,PIPEjar_locati…

Invalid value after matching string using regex [duplicate]

This question already has answers here:Incrementing a number at the end of string(2 answers)Closed 3 years ago.I am trying to match strings with an addition of 1 at the end of it and my code gives me t…

How to fetch specific data from same class div using Beautifulsoup

I have a link : https://www.cagematch.net/?id=2&nr=448&gimmick=Adam+Pearce In this link there data in divs with same class name. But I want to fetch specifi div. Like I want to fetch current g…

Python Matplotlib Box plot

This is my dataframe:{Parameter: {0: A, 1: A, 2: A, 3: A, 4: A, 5: A, 6: A, 7: A},Site: {0: S1,1: S2,2: S1,3: S2,4: S1,5: S2,6: S1,7: S2},Value: {0: 2.3399999999999999,1: 2.6699999999999999,2: 2.560000…

How to send turtle to random position?

I have been trying to use goto() to send turtles to a random position but I get an error when running the program.I am lost on how else to do this and not sure of other ways. My current code is:t1.shap…

How to scrape all p-tag and its corresponding h2-tag with selenium?

I want to get title and content of article: example web :https://facts.net/best-survival-movies/ I want to append all p in h2[tcontent-title]and the result expected is: title=[title1, title2, title3]co…

Tkinter: Window not showing image

I am new to GUI programming and recently started working with tKinter.My problem is that the program wont show my image, Im suspecing that it is my code that is wrong, however, I would like somone to e…

print dictionary minus two elements

Python 3.6All debug output is from PyCharm 2017.1.2I have a program that gets to this portion of the code:if len(errdict) == 21:for k, v in errdict.items():if k == packets output or bytes:continueprint…