I try to plot several data I receive over the USART serial bus from a microcontroller in python. It would be fine, if I could plot all the data in parallel and in realtime.
When I use a single plot, the data is plotted in realtime but when I use subplots, the data has more and more delay, also if I only plot one subchannel. Has someone any Idea why subplots in python are so much slower?
I measured also the time consumption for the function update(), it seems to be 2ms or less. The Data I receive only every 5ms or more. How can I improve the speed?
Kind regards: Sebastian T.
Here is my code
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import time
from collections import deque
#SERIAL#######################################################
try:
ser = serial.Serial()
ser.baudrate=115200;
ser.port = 'COM7'
ser.open()
except:
ser.close()
print('Problem occured')
ser.flushInput()
ser.flushOutput()
#PLOT##########################################################
MAX_X = 250 #width of graph
MAX_Y = 70000 #height of graph
# intialize line to horizontal line on 0
line1 = deque([0.0]*MAX_X, maxlen=MAX_X)
line2 = deque([0.0]*MAX_X, maxlen=MAX_X)
line3 = deque([0.0]*MAX_X, maxlen=MAX_X)
line4 = deque([0.0]*MAX_X, maxlen=MAX_X)
line5 = deque([0.0]*MAX_X, maxlen=MAX_X)
plt.close('all')
fig, (ax1,ax2,ax3,ax4) = plt.subplots(4,1)
l1, = ax1.plot([], [])
l2, = ax2.plot([], [])
l3, = ax3.plot([], [])
l4, = ax4.plot([], [])
l=[l1,l2,l3,l4]
for ax in [ax1,ax2,ax3,ax4]:
ax.set_ylim(-(MAX_Y/2),MAX_Y/2)
ax.set_xlim(-(MAX_X/2),MAX_X/2)
ax.grid()
def update(fn, data):
try:
t = time.time()
#prepare Data
data_raw = ser.readline()
data_raw = data_raw.split(',')
data_raw = data_raw[1::2]
#Update Plots
line1.append(int(data_raw[0]))
line2.append(int(data_raw[1]))
line3.append(int(data_raw[2]))
line4.append(int(data_raw[3]))
#Set Data
l[0].set_data(range(-MAX_X/2, MAX_X/2), line1)
l[1].set_data(range(-MAX_X/2, MAX_X/2), line2)
l[2].set_data(range(-MAX_X / 2, MAX_X / 2), line3)
l[3].set_data(range(-MAX_X / 2, MAX_X / 2), line4)
print(time.time() - t)
except:
print('exception')
ser.close()
ani = anim.FuncAnimation(fig,update,fargs=(0,),frames=1, interval=100)
plt.show()