Home > Net >  How to show sliding windows of a numpy array with matplotlib FuncAnimation
How to show sliding windows of a numpy array with matplotlib FuncAnimation

Time:10-29

I am developing a simple algorithm for the detection of peaks in a signal. To troubleshoot my algorithm (and to showcase it), I would like to observe the signal and the detected peaks all along the signal duration (i.e. 20 minutes at 100Hz = 20000 time-points).

I thought that the best way to do it would be to create an animated plot with matplotlib.animation.FuncAnimation that would continuously show the signal sliding by 1 time-points and its superimposed peaks within a time windows of 5 seconds (i.e. 500 time-points). The signal is stored in a 1D numpy.ndarray while the peaks information are stored in a 2D numpy.ndarray containing the x and y coordinates of the peaks.

This is a "still frame" of how the plot would look like.

enter image description here

Now the problem is that I cannot wrap my head around the way of doing this with FuncAnimation.

If my understanding is correct I need three main pieces: the init_func parameter, a function that create the empty frame upon which the plot is drawn, the func parameter, that is the function that actually create the plot for each frame, and the parameter frames which is defined in the help as Source of data to pass func and each frame of the animation.

Looking at examples of plots with FuncAnimation, I can only find use-cases in which the data to plot are create on the go, like enter image description here

CodePudding user response:

Probably not exactly what you want, but hope it can help,

import neurokit2 as nk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from sklearn.preprocessing import MinMaxScaler
import numpy as np
from matplotlib.animation import FuncAnimation


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# This function is called periodically from FuncAnimation
def animate(i, xs, ys):

    xs = xs[i]
    ys = ys[i]

    # Draw x and y lists
    ax.clear()
    ax.plot(xs, ys)

if __name__=="__main__":
   
  data = nk.ecg_simulate(duration = 50, sampling_rate = 100, noise = 0.05, random_state = 1)
  scaler = MinMaxScaler()
  scaled_arr = scaler.fit_transform(data.reshape(-1,1))
  
  ys = scaled_arr.flatten()
  ys = [ys[0:50*i] for i in range(1, int(len(ys)/50) 1)]
  xs = [np.arange(0, len(ii)) for ii in ys ]
  
 
  ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=500)
  ani.save('test.gif')

enter image description here

  • Related