Python matplotlib plot /graph partial refresh from starting point

Viewed 368

Sorry I am a bit new to python and matplotlib so I dont know if I am asking it correctly. As of now I am plotting graphs where I collect an array of integers coming via serial port and refreshing the whole plot area at once. Now I want to do partial refresh (idk if it is the correct word) something like a PPG/ECG trace where once the line/trace reaches the end of plot area it starts from beginning, something like in the example here [1]: http://theblogofpeterchen.blogspot.com/2015/02/html5-high-performance-real-time.html. I do understand that if I keep on appending the serial port data and plotting it as soon as it arrives will keep on extending the plot forward but I have no clue how to return back at the the beginning point and redraw it gradually as in ECG.

Kindly help in this regard

Thank you

1 Answers

I have a solution below using FuncAnimation.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy.misc import electrocardiogram


ecg = electrocardiogram()[0:1000]

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], '-')

# this is repeat length
n = 200


def init():
    ax.set_xlim(0, n)
    ax.set_ylim(-1, 2)
    return ln,

def update(i):
    # update xlim of axes
    if i % n == 0:
        ln.axes.set_xlim(int(i/n)*n, int(i/n)*n+n)
    else:
        xdata.append(i)
        ydata.append(ecg[i])
        ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=1000, init_func=init, blit=True, interval=10, repeat=False)
Related