I am showing real time plot from Arduino sensors with matplotlib and Python 3.9.13.
I encounter a problem which is: The pyplot window keeps opening a new one everytime a new data is obtained from the Arduino' sensor, instead of refreshing on the current pyplot window.
How to fix it?
If I try to close one of the old pyplot window all pyplot windows will be closed, which is troublesome.
This is my code :
import serial
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from drawnow import *
tempC=[]
altitude=[]
PPMCO2=[]
MQ7CO=[]
arduinoData = serial.Serial('/dev/ttyACM0', 115200)
plt.ion()
cnt=0
def makeFig():
fig, axs = plt.subplots(2,2)
(ax1, ax2), (ax3, ax4) = axs
ax1.grid(True)
ax1.plot(PPMCO2, 'ro-', label='CO2 (from MQ135)')
ax1.legend(loc='upper left')
ax2.grid(True)
ax2.plot(MQ7CO, 'g*-', label='CO (from MQ7)')
ax2.ticklabel_format(useOffset=False)
ax2.legend(loc='upper right')
ax3.grid(True)
ax3.plot(tempC, 'mp-', label='Degrees C')
ax3.ticklabel_format(useOffset=False)
ax3.legend(loc='upper right')
ax4.grid(True)
ax4.plot(altitude, 'kD-', label='Altitude (m)')
ax4.ticklabel_format(useOffset=False)
ax4.legend(loc='upper right')
while True:
while (arduinoData.inWaiting()==0):
pass
arduinoString = arduinoData.readline()
#print(arduinoString)
s = str(arduinoString)
s = s.replace('b\'','')
s = s.replace('\\r\\n\'','')
f = str(arduinoString)
f = f.replace('b\'','[')
f = f.replace('\\r\\n\'','],')
print(s)
print(f)
dataArray = s.split(',')
temp = float(dataArray[0])
alt = float(dataArray[1])
co2 = float(dataArray[2])
co = float(dataArray[3])
tempC.append(temp)
altitude.append(alt)
PPMCO2.append(co2)
MQ7CO.append(co)
drawnow(makeFig)
plt.pause(.000001)
cnt=cnt+1
if(cnt>50):
tempC.pop(0)
altitude.pop(0)
PPMCO2.pop(0)
MQ7CO.pop(0)