I'm trying to create live data plot. This is my script:
import time
import serial
import comport as com
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animate(i, dataList, ser):
arduinoData_string = ser.readline().decode('ascii') # Decode receive Arduino data as a formatted string
# print(i) # 'i' is a incrementing variable based upon frames = x argument
try:
arduinoData_float = float(arduinoData_string) # Convert to float
dataList.append(arduinoData_float) # Add to the list holding the fixed number of points to animate
except: # Pass if data point is bad
pass
dataList = dataList[-50:] # Fix the list size so that the animation plot 'window' is x number of points
ax.clear() # Clear last data frame
ax.plot(dataList) # Plot new data frame
ax.set_ylim([0, 1200]) # Set Y axis limit of plot
ax.set_title("Arduino Data") # Set title of figure
ax.set_ylabel("Value") # Set title of y axis
dataList = [] # Create empty list variable for later use
fig = plt.gcf() # Create Matplotlib plots fig is the 'higher level' plot window
ax = fig.add_subplot(111) # Add subplot to main fig window
ser = com.ini('COM2')
time.sleep(2) # Time delay for Arduino Serial initialization
# Matplotlib Animation Fuction that takes takes care of real time plot.
# Note that 'fargs' parameter is where we pass in our dataList and Serial object.
# ani = FuncAnimation(fig, animate, frames=100, fargs=(dataList, ser), interval=100)
ani = animation.FuncAnimation(fig, animate, frames=100, fargs=(dataList, ser), interval=100)
plt.show() # Keep Matplotlib plot persistent on screen until it is closed
ser.close()
When I try to run it, I got this message: MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
.
I'm using latest PyCharm version just to be sure the right default backend is used. Matplotlib version is 3.7.1.
Does anyone have an idea how to deal with error and how to fix it?
I should've switched the animation backend. By default on Windows 10 in PyCharm, matplotlib uses module://backend_interagg
. I switched to TkAgg backend by placing this code in the beggining of the script
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Then I ask ChatGPT, how I can improve my code and make it works properly. So, It gives me an akward code, but it works. And now I can plot live data!