Search code examples
python-3.xmatplotlibanimationreal-timepyserial

python real time plot using funcanimation giving blank graph


I am trying to plot a realtime graph using matplotlib's FuncAnimation class. The data is coming from arduino using pyserial library. I have tried the following code to plot in real time but the graph is empty, I can see the axes, ticks etc but not the plot. Can anyone help me what I am doing wrong here? Thank you in advance.

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import serial
import os
import numpy as np
import datetime
import pandas as pd


fig = plt.figure()  

port= 'COM10'
baudrate = 9600
timeout = 2

ser = serial.Serial(port=port, baudrate=baudrate, timeout=timeout)

def animate(i):
    j = 0  
    while True:
        try:
            loadcells = ser.readline()
            loadcells = loadcells.decode('utf-8').rstrip().replace('\t','').split(',')
            print(loadcells)
            loadcell1 = float(loadcells[0])
            # loadcell2 = loadcells[1]
            plt.cla()
            plt.plot(loadcell1)
            plt.pause(0.001)
            j+=1
            # plt.plot(loadcell2)
        except Exception as e:
            print(e)
            continue
        except KeyboardInterrupt as e1:
            print(e1)
            ser.close()

        

anim = FuncAnimation(fig, animate,    
                    frames = 200,  
                    interval = 0.1,  
                    blit = False) 

plt.tight_layout()
plt.show()

Solution

  • You should not have an infinite loop in animate(). FuncAnimation works by calling animate() repeatedly at a pre-defined interval (interval=0.1).

    You need to rewrite your animate() function where you read the serial port, plot the result, and return (no pause() either).