0

The problem

I need the animation to go fluid, but it is ploting frame by frame. The code is running in Jupyter Notebook.

Here are the libraries

import numpy as np
from matplotlib import pyplot as plt
from scipy import signal as sp

Creating the functions to convolve

t_ini=0
t_final = 11
dt=0.1
t = np.arange(t_ini,t_final,dt)
expo = np.exp(-t)*np.piecewise(t,t>=0,[1,0])
t1 = np.arange(0,10,0.1)
s = np.sin(t1)
conv_=sp.convolve(s,expo,'full')
n_conv=np.arange(min(t1)+min(t),max(t1)+max(t)+0.1,0.1)
y = [0] * len(conv_)
t2 = [0] * len(n_conv)

Here is the plotting

i = 0
for x in n_conv:

    y[i] = conv_[i]
    plt.cla()
    t2[i] = n_conv[i]
    plt.plot(t2,y)
    plt.show()
    plt.pause(0.5)

    i = i+1
Daniel Daza
  • 57
  • 1
  • 13

1 Answers1

0

matplotlib provides for instance ArtistAnimation that allows a seamless animation of precalculated graphs. I just added a couple of lines to your code. Only thing I changed was to use enumerate to improve your code

import numpy as np
from matplotlib import pyplot as plt
from scipy import signal as sp
import matplotlib.animation as anim

t_ini=0
t_final = 11
dt=0.1
t = np.arange(t_ini,t_final,dt)
expo = np.exp(-t)*np.piecewise(t,t>=0,[1,0])
t1 = np.arange(0,10,0.1)
s = np.sin(t1)
conv_=sp.convolve(s,expo,'full')
n_conv=np.arange(min(t1)+min(t),max(t1)+max(t)+0.1,0.1)
y = [0] * len(conv_)
t2 = [0] * len(n_conv)

#prepare figure for display
fig = plt.figure()
ax = plt.axes()

#create list to collect graphs for animation
img = []
for i, x in enumerate(n_conv):

    y[i] = conv_[i]
    t2[i] = n_conv[i]
    #append new graphs to  list
    newpic, = ax.plot(t2, y, c= "blue")
    img.append([newpic])

#animate the list of precalculated graphs
ani = anim.ArtistAnimation(fig, img, interval = 50)
plt.show()

Output:

enter image description here

Mr. T
  • 11,960
  • 10
  • 32
  • 54
  • something is wrong in there it just give me a blank graph – Daniel Daza Apr 08 '18 at 18:02
  • Hm. I just pasted this code in my IDE and it animates the curve. What is your matplotlib version and your backend? – Mr. T Apr 08 '18 at 18:33
  • my matplotlib version is 2.0.0 what do you mean by my backend? – Daniel Daza Apr 08 '18 at 18:44
  • Ok when i run it from the cli in a .py file it animates the curve fine but in jupyter notebook it doesnt work. Why this could happen? – Daniel Daza Apr 08 '18 at 18:48
  • I don't use jupyter notebook, but seemingly some backends don't support animations, see here: https://stackoverflow.com/a/46878531/8881141 or here: https://stackoverflow.com/a/43447370/8881141 – Mr. T Apr 08 '18 at 19:51