How to wait until matplotlib animation ends? - python

Consider the following code directly taken from the Matplotlib documentation:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time # optional for testing only
import cv2 # optional for testing only
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y), animated=True)
def updatefig(*args):
global x, y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
This work fine on my system. Now, try to append the following piece of code to the above code:
while True:
#I have tried any of these 3 commands, without success:
pass
#time.sleep(1)
#cv2.waitKey(10)
What happens is that the program freezes. Apparently, the "Animation" class of Matplotlib runs the animation in a separate thread. So I have the 2 following questions:
1) If the process runs in a separate thread, why is it disturbed by the subsequent loop ?
2) How to say to python to wait until the animation has ended ?

For me, copying into ipython works as expected (animation plays first then the infinite loop) but when running the script it freezes.
1) I'm not sure exactly how cpython handles multi-threading, especially when combined with a particular matplotlib backend but it seems to be failing here. One possibility is to be explicit about how you want to use threads, by using
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import multiprocessing as mp
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y), animated=True)
def updatefig(*args):
global x, y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
return im,
#A function to set thread number 0 to animate and the rest to loop
def worker(num):
if num == 0:
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
else:
while True:
print("in loop")
pass
return
# Create two threads
jobs = []
for i in range(2):
p = mp.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
Which defines two threads and sets one to work on animation, one to loop.
2) To fix this, as suggested by #Mitesh Shah, you can use plt.show(block=True). For me, the script then behaves as expected with animation and then loop. Full code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y), animated=True)
def updatefig(*args):
global x, y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show(block=True)
while True:
print("in loop")
pass
UPDATE: Alternative is to simply use interactive mode,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
plt.ion()
plt.show()
def f(x, y):
return np.sin(x) + np.cos(y)
def updatefig(*args):
global x, y
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y))
for i in range(500):
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
plt.draw()
plt.pause(0.0000001)

Thanks to the help of Ed Smith and MiteshNinja, I have finally succeeded in finding a robust method that works not only with the Ipython console, but also with the Python console and the command line. Furthermore, it allows total control on the animation process. Code is self explanatory.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from multiprocessing import Process
import time # optional for testing only
import matplotlib.animation as animation
# A. First we define some useful tools:
def wait_fig():
# Block the execution of the code until the figure is closed.
# This works even with multiprocessing.
if matplotlib.pyplot.isinteractive():
matplotlib.pyplot.ioff() # this is necessary in mutliprocessing
matplotlib.pyplot.show(block=True)
matplotlib.pyplot.ion() # restitute the interractive state
else:
matplotlib.pyplot.show(block=True)
return
def wait_anim(anim_flag, refresh_rate = 0.1):
#This will be used in synergy with the animation class in the example
#below, whenever the user want the figure to close automatically just
#after the animation has ended.
#Note: this function uses the controversial event_loop of Matplotlib, but
#I see no other way to obtain the desired result.
while anim_flag[0]: #next code extracted from plt.pause(...)
backend = plt.rcParams['backend']
if backend in plt._interactive_bk:
figManager = plt._pylab_helpers.Gcf.get_active()
if figManager is not None:
figManager.canvas.start_event_loop(refresh_rate)
def draw_fig(fig = None):
#Draw the artists of a figure immediately.
#Note: if you are using this function inside a loop, it should be less time
#consuming to set the interactive mode "on" using matplotlib.pyplot.ion()
#before the loop, event if restituting the previous state after the loop.
if matplotlib.pyplot.isinteractive():
if fig is None:
matplotlib.pyplot.draw()
else:
fig.canvas.draw()
else:
matplotlib.pyplot.ion()
if fig is None:
matplotlib.pyplot.draw()
else:
fig.canvas.draw()
matplotlib.pyplot.ioff() # restitute the interactive state
matplotlib.pyplot.show(block=False)
return
def pause_anim(t): #This is taken from plt.pause(...), but without unnecessary
#stuff. Note that the time module should be previously imported.
#Again, this use the controversial event_loop of Matplotlib.
backend = matplotlib.pyplot.rcParams['backend']
if backend in matplotlib.pyplot._interactive_bk:
figManager = matplotlib.pyplot._pylab_helpers.Gcf.get_active()
if figManager is not None:
figManager.canvas.start_event_loop(t)
return
else: time.sleep(t)
#--------------------------
# B. Now come the particular functions that will do the job.
def f(x, y):
return np.sin(x) + np.cos(y)
def plot_graph():
fig = plt.figure()
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = fig.gca().imshow(f(x, y))
draw_fig(fig)
n_frames = 50
#==============================================
#First method - direct animation: This use the start_event_loop, so is
#somewhat controversial according to the Matplotlib doc.
#Uncomment and put the "Second method" below into comments to test.
'''for i in range(n_frames): # n_frames iterations
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
draw_fig(fig)
pause_anim(0.015) # plt.pause(0.015) can also be used, but is slower
wait_fig() # simply suppress this command if you want the figure to close
# automatically just after the animation has ended
'''
#================================================
#Second method: this uses the Matplotlib prefered animation class.
#Put the "first method" above in comments to test it.
def updatefig(i, fig, im, x, y, anim_flag, n_frames):
x = x + i * np.pi / 15.
y = y + i * np.pi / 20.
im.set_array(f(x, y))
if i == n_frames-1:
anim_flag[0] = False
anim_flag = [True]
animation.FuncAnimation(fig, updatefig, repeat = False, frames = n_frames,
interval=50, fargs = (fig, im, x, y, anim_flag, n_frames), blit=False)
#Unfortunately, blit=True seems to causes problems
wait_fig()
#wait_anim(anim_flag) #replace the previous command by this one if you want the
#figure to close automatically just after the animation
#has ended
#================================================
return
#--------------------------
# C. Using multiprocessing to obtain the desired effects. I believe this
# method also works with the "threading" module, but I haven't test that.
def main(): # it is important that ALL the code be typed inside
# this function, otherwise the program will do weird
# things with the Ipython or even the Python console.
# Outside of this condition, type nothing but import
# clauses and function/class definitions.
if __name__ != '__main__': return
p = Process(target=plot_graph)
p.start()
print('hello', flush = True) #just to have something printed here
p.join() # suppress this command if you want the animation be executed in
# parallel with the subsequent code
for i in range(3): # This allows to see if execution takes place after the
#process above, as should be the case because of p.join().
print('world', flush = True)
time.sleep(1)
main()

We can run the animation function in a separate thread. Then start that thread. Once a new thread is created, the execution will continue.
We then use p.join() to wait for our previously created thread to finish execution. As soon as the execution finished (or terminates for some reason) the code will continue further.
Also matplotlib works differently in Interactive Python shells vs. system command line shells, the below code should work for both these scenarios:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from multiprocessing import Process
import time # optional for testing only
#import cv2 # optional for testing only
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y), animated=True)
def plot_graph(*args):
def updatefig(*args):
global x, y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
p = Process(target=plot_graph)
p.start()
# Code here computes while the animation is running
for i in range(10):
time.sleep(1)
print('Something')
p.join()
print("Animation is over")
# Code here to be computed after animation is over
I hope this helped! You can find more information here: Is there a way to detach matplotlib plots so that the computation can continue?
Cheers! :)

Related

Funcanimation with bit=True is not updating x axis and not making sense with maximizing the window

I am trying to just have a simple life by getting a real-time plot functionality with blit=True but what I get is a plot with wrong x-axis limits and the plot changes when I maximize the plot window.
I want to have a plot of 50000 (say) points made in one go and then use funcanimation to call animate() to update the existing plot with set_data(x,y). Everything works fine if blit=False but I want to have blitting in my GUI. Please help with your thoughts. Attaching a short video for your reference along with the code.
I am pasting my code below:
Thanks in advance!
import time
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from random import randrange
fig = plt.figure(figsize=(6, 3))
varLen = 1000
x=[r for r in range(varLen-300)]
y=[randrange(0, 10) for r in range(varLen-300)]
y2=[10+randrange(0, 10) for r in range(varLen-300)]
# y=[]
# y2=[]
print(type(x))
ln, = plt.plot(x, y, '-')
ln2, = plt.plot(x, y2, '-')
def update(frame):
start=time.time()
global x, y, y2
x.append(x[-1]+1)
val=randrange(0, 10)
y.append(val)
y2.append(10+val)
# print(len(x), len(y), len(y2))
x=x[-varLen:]
y = y[-varLen:]
y2 = y2[-varLen:]
ln.set_data(x, y)
ln2.set_data(x,y2)
# ln.set_data(frame, randrange(0, 10))
# ln2.set_data(frame, 10+randrange(0, 10))
fig.gca().relim()
fig.gca().autoscale_view()
print(f'Time (ms): {round((time.time() - start)*1000,2)}')
return ln,ln2,
animation = FuncAnimation(fig, update, interval=1, blit=True)
plt.show()

Create an animation with Python3 and Matplotlib

I tried to create an animation with matplotlib.pyplot and matplotlib.animation and I encountured two problems:
1st is that, I went to matplotlib animation page and then I tried their code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are just animating one artist, the image, in
# each frame
ims = []
for i in range(60):
x += np.pi / 15.
y += np.pi / 20.
im = plt.imshow(f(x, y), animated=True)
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
repeat_delay=1000)
# ani.save('dynamic_images.mp4')
plt.show()
I got an error: AttributeError: 'function' has no attribute 'canvas' (I re-tried and I didn't get any error...
2nd, when I uncomment ani.save('dynamic_images.mp4') I get this error: TypeError: 'MovieWriterRegistry' object is not an iterator. This one bothers me a lot more. If you have any solution about this last problem, please let me now.
WolfGang1710.
As you can read in the documentation of the method Animation.save the default writer is 'ffmpeg'. Therefore, you need to have ffmpeg installed for it to work.

Catch error in update function of matplotlib animation

I'd like to be able to catch an error while plotting using the matplotlib animation function.
This is necessary for me as I have a program where it can happen that an error occurs in the updatefig function after a couple of loops. I'd like to then continue in the script to save all the data generated up to that point.
Instead of throwing an error, running the code below will just lead to the following output:
Process finished with exit code 1
I tried to put the try except clause at all positions I could think of but was never able to go to the last print().
See this MWE (taken from here):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
counter = 0
im = plt.imshow(f(x, y), animated=True)
def updatefig(*args):
global x, y, counter
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
counter += 1
# do something that might fail at one point (and will fail in this example)
if counter > 10:
b = 0
print('bla ' + b) # error
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
print('do other stuff now, e.g. save x and y')
There is an error because you are attempting to concatenate a string with an int:
Option 1:
correct the error:
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
counter = 0
im = plt.imshow(f(x, y), animated=True)
def updatefig(*args):
global x, y, counter
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
counter += 1
# do something that will not fail
if counter > 10:
b = 0
print('bla ' + str(b))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
print('do other stuff now, e.g. save x and y')
option 2:
catch the Error, save the data, and continue:
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
counter = 0
im = plt.imshow(f(x, y), animated=True)
def save_if_error():
print('do other stuff now, e.g. save x and y')
def updatefig(*args):
global x, y, counter
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
counter += 1
# do something that might fail at one point and catch the error, save the data and continue
if counter > 10:
b = 0
try:
print('bla ' + b) # error
except TypeError:
print("save the data here")
save_if_error()
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()

Creating animation in python from Octave code

I am new to coding and have been trying to create an animation in python from a previously generated code in Octave (below). So far I have not had any success, besides plotting an unanimated scatter plot. Any tips or help would be greatly appreciated.
clear;
N = 100;
NT = 200;
for i=1:N
x(i) = 0;
y(i) = 0;
end
plot(x,y,'o');
axis([0 20 -10 10]);
for k = 1 : NT
x = x + normrnd(0.1,0.1,1,N);
y = y + normrnd(0,0.1,1,N);
temp = mod(k,1);
if temp == 0
plot(x,y,'s');
axis([0 20 -10 10]);
drawnow
end
end
Here is one of the many attempts that did not work (below).
import numpy as np
import matplotlib as plt
from pylab import *
from matplotlib import animation
import random
n=100
nt=2000
m=20
mu=0
sigma=0.1
p=100
fig = plt.figure()
ax = plt.axes(xlim=(-10, 10), ylim=(-10, 10))
scat, = ax.plot([], [])
# initialization function: plot the background of each frame
def init():
x = 0
y = 0
return scat,
# animation function. This is called sequentially
def animate(i):
for k in range (1,nt):
x = x+ np.random.normal(mu, sigma, n)
return scat,
for i in range (1,nt):
y = y+ np.random.normal(mu, sigma, n)
return scat,
anim = animation.FuncAnimation(fig, animate,
init_func=init,frames=200, interval=20, blit=True)
plt.show()
you could do the animation using Octave of Python.
For the python script I think that one of the problems was to set a return within a loop, therefore several times for one function def animate. Looking at the animation doc https://matplotlib.org/api/animation_api.html I edited your example and got this which I think might be usefull:
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from matplotlib.animation import FuncAnimation
import random
n=100
sigma=0.1
nt=2000
fig, ax = plt.subplots()
xdata, ydata = [0.0], [0.0]
ln, = plt.plot([], [], 'ro', animated=True)
def init():
ax.set_xlim( 0, 20)
ax.set_ylim(-10, 10)
return ln,
def update(frame):
global xdata
global ydata
xdata = xdata + np.random.normal(0.1, sigma, n)
ydata = ydata + np.random.normal(0.0, sigma, n)
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
You could also do the animation using octaves print command to generate several pngs and use gimp to produce a gif or embbed in LaTeX the pngs using animate.
Best,
Jorge

Matplotlib animation in real time

In the example below I want to make an animation where a point moves around a circle in T seconds (for example T=10). However it is a lot slower and doesn't work. So, what is wrong with my code and how to fix it? As far as I understand the api (http://matplotlib.org/api/animation_api.html) setting interval=1 should update the figure every millisecond.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
R = 3
T = 10
fig = plt.figure()
fig.set_dpi(300)
fig.set_size_inches(7, 6.5)
ax = plt.axes(xlim=(-10, 10), ylim=(-R*1.5, R*1.5))
ax.set_aspect('equal')
patch = plt.Circle((0, 0), 0.1, fc='r')
looping = plt.Circle((0,0),R,color='b',fill=False)
ax.add_artist(looping)
time_text = ax.text(-10,R*1.2,'',fontsize=15)
def init():
time_text.set_text('')
patch.center = (0, 0)
ax.add_patch(patch)
return patch,time_text,
def animate(i):
t=i/1000.0
time_text.set_text(t)
x, y = patch.center
x = R*np.sin(t/T*2*np.pi)
y = R*np.cos(t/T*2*np.pi)
patch.center = (x, y)
return patch,time_text
slow_motion_factor=1
anim = animation.FuncAnimation(fig, animate,
init_func=init,
frames=10000,
interval=1*slow_motion_factor,
blit=True)
plt.show()
I should add that the problem depends on the machine where I run the program. For example on a old Intel dualcore (P8700) (that's the box where the program should run), it is considerable slower than on a newer haswell i7 desktop cpu. But in the latter case it is also much slower as intended.
The problem is, that your computer is not fast enough, to deliver a new image every 1 ms. Which is kind of expected.
You should go for a more realistic speed. 25 frames per second should be enough
and also be possible to render in time.
I also made a few adjustment to you code, mostly style and more semantic variable names.
The biggest change was adapting this answer to your code to get rid of the first frame being still there after the init:
Matplotlib animation: first frame remains in canvas when using blit
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
R = 3
T = 10
time = 3 * T
slow_motion_factor = 1
fps = 50
interval = 1 / fps
fig = plt.figure(figsize=(7.2, 7.2))
ax = fig.add_subplot(1, 1, 1, aspect='equal')
ax.set_xlim(-1.5 * R, 1.5 * R)
ax.set_ylim(-1.5 * R, 1.5 * R)
runner = plt.Circle((0, 0), 0.1, fc='r')
circle = plt.Circle((0, 0), R, color='b', fill=False)
ax.add_artist(circle)
time_text = ax.text(1.1 * R, 1.1 * R,'', fontsize=15)
def init():
time_text.set_text('')
return time_text,
def animate(i):
if i == 0:
ax.add_patch(runner)
t = i * interval
time_text.set_text('{:1.2f}'.format(t))
x = R * np.sin(2 * np.pi * t / T)
y = R * np.cos(2 * np.pi * t / T)
runner.center = (x, y)
return runner, time_text
anim = animation.FuncAnimation(
fig,
animate,
init_func=init,
frames=time * fps,
interval=1000 * interval * slow_motion_factor,
blit=True,
)
plt.show()

Categories