Related
I am trying to put text in a matplotlib animation. (Hopefully outside the plot, but I am not worrying about that yet)
I tried to follow this solution, however my code is a bit complicated in that it does not gives only one line every time.
Here is my code
import math
import argparse
import os
import json
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation ,FFMpegWriter
line_x=[ 0,1,2,3,4,5,6,7,8,9,10,11,12 ]
line1_y=[ 3,5,7,9,11,19,23,26,29,31,37,40,45 ]
line2_y=[0,2,5,7,10,10,8,5,3,2,1,3,5]
line3_y=[39,38,32,29,26,22,19,13,10,8,7,6,3]
set_lines=[line1_y,line2_y,line3_y]
n_lineas=[1,2,3,1,3,2,3,1,3,2,1,2]
show=True
thecolors=['blue','red','violet']
thelegends=['unus','duo','tres']
print(sys.argv)
if len(sys.argv)==2 and sys.argv[1]=='movie':
show=False
def get_n(thelist,c):
while(c>=len(thelist)):
c-len(thelist)
return thelist[c]
class Update:
def __init__(self,ax,limit_x):
self.ax = ax
self.lx=limit_x
if limit_x!=0:
self.ax.set_xlim(0,limit_x)
self.ax.set_ylim(0,45)
self.ax.set_aspect('equal')
self.ax.grid(True)
self.lines=()
self.counter=0
self.text=self.ax.text(0,0,'')
def __call__(self, frame):
print("Frame: ",frame)
lines=[]
self.ax.cla()
self.ax.set_xlim(0,self.lx)
self.ax.set_ylim(0,45)
self.ax.grid(True)
self.ax.set_xlabel("Y (meters)")
self.ax.set_ylabel("X (meters)")
n_lines_this_time=get_n(n_lineas,self.counter)
self.counter+=1
print(n_lines_this_time,"lines this time")
for myline in range(n_lines_this_time):
#line,=self.ax.plot([],[],'.-',color=gt_color,label=legend)
line,=self.ax.plot([],[],'.-',color=thecolors[myline],label=thelegends[myline])
x = []
y = []
for v in range(13):
x.append(line_x[v])
y.append(set_lines[myline][v])
line.set_xdata(x)
line.set_ydata(y)
lines.append(line)
plt.legend()
self.lines=tuple(lines)
self.text.set_text("Frame "+str(frame))
self.text.set_position((0,0))
#return self.lines,self.text #<---HERE this does not work!!!
return self.lines
def init(self):
print("Init")
line,=self.ax.plot([],[])
self.ax.grid(True)
self.ax.set_xlabel("Y (meters)")
self.ax.set_ylabel("X (meters)")
self.text.set_text('')
self.text.set_position((0,0))
return line,self.text,
#return line,
fig, ax = plt.subplots(1, 1,figsize=(10,10))
plt.gcf().canvas.mpl_connect(
'key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plt.xlabel("Y (meters)")
plt.ylabel("X (meters)")
plt.legend()
ug_i = Update(ax,13)
anim = FuncAnimation(fig, ug_i,init_func=ug_i.init, frames=10, interval=1000, blit=True,repeat=False)
if not show:
writervideo = FFMpegWriter(fps=1)
anim.save('whatever.mp4', writer=writervideo)
print('done')
plt.close()
else:
#plt.legend()
plt.show()
In the current state, the text does not show (of course) but when I try to return it (as marked above in a comment ("HERE") ) it crashes giving me the error
Traceback (most recent call last):
File "/home/kansai/miniconda3/envs/roscv/lib/python3.7/site-packages/matplotlib/backend_bases.py", line 1194, in _on_timer
ret = func(*args, **kwargs)
File "/home/kansai/miniconda3/envs/roscv/lib/python3.7/site-packages/matplotlib/animation.py", line 1442, in _step
still_going = Animation._step(self, *args)
File "/home/kansai/miniconda3/envs/roscv/lib/python3.7/site-packages/matplotlib/animation.py", line 1173, in _step
self._draw_next_frame(framedata, self._blit)
File "/home/kansai/miniconda3/envs/roscv/lib/python3.7/site-packages/matplotlib/animation.py", line 1192, in _draw_next_frame
self._draw_frame(framedata)
File "/home/kansai/miniconda3/envs/roscv/lib/python3.7/site-packages/matplotlib/animation.py", line 1748, in _draw_frame
key=lambda x: x.get_zorder())
File "/home/kansai/miniconda3/envs/roscv/lib/python3.7/site-packages/matplotlib/animation.py", line 1748, in <lambda>
key=lambda x: x.get_zorder())
AttributeError: 'tuple' object has no attribute 'get_zorder'
Aborted (core dumped)
What is failing and how can I display the text? (if outside the plot much better)
After un-commenting your line of code, I didn't get any error, however the text was not visible. So, instead of using ax.text I tried fig.text: now the text is visible outside the plotting area.
import math
import argparse
import os
import json
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation ,FFMpegWriter
line_x=[ 0,1,2,3,4,5,6,7,8,9,10,11,12 ]
line1_y=[ 3,5,7,9,11,19,23,26,29,31,37,40,45 ]
line2_y=[0,2,5,7,10,10,8,5,3,2,1,3,5]
line3_y=[39,38,32,29,26,22,19,13,10,8,7,6,3]
set_lines=[line1_y,line2_y,line3_y]
n_lineas=[1,2,3,1,3,2,3,1,3,2,1,2]
show=True
thecolors=['blue','red','violet']
thelegends=['unus','duo','tres']
# print(sys.argv)
# if len(sys.argv)==2 and sys.argv[1]=='movie':
# show=False
def get_n(thelist,c):
while(c>=len(thelist)):
c-len(thelist)
return thelist[c]
class Update:
def __init__(self,fig,ax,limit_x):
self.ax = ax
self.lx=limit_x
if limit_x!=0:
self.ax.set_xlim(0,limit_x)
self.ax.set_ylim(0,45)
self.ax.set_aspect('equal')
self.ax.grid(True)
self.lines=()
self.counter=0
self.text=fig.text(0.15,0.5,'')
def __call__(self, frame):
print("Frame: ",frame)
lines=[]
self.ax.cla()
self.ax.set_xlim(0,self.lx)
self.ax.set_ylim(0,45)
self.ax.grid(True)
self.ax.set_xlabel("Y (meters)")
self.ax.set_ylabel("X (meters)")
n_lines_this_time=get_n(n_lineas,self.counter)
self.counter+=1
print(n_lines_this_time,"lines this time")
for myline in range(n_lines_this_time):
#line,=self.ax.plot([],[],'.-',color=gt_color,label=legend)
line,=self.ax.plot([],[],'.-',color=thecolors[myline],label=thelegends[myline])
x = []
y = []
for v in range(13):
x.append(line_x[v])
y.append(set_lines[myline][v])
line.set_xdata(x)
line.set_ydata(y)
lines.append(line)
plt.legend()
self.lines=tuple(lines)
self.text.set_text("Frame "+str(frame))
return self.lines,self.text #<---HERE this does not work!!!
return self.lines
def init(self):
print("Init")
line,=self.ax.plot([],[])
self.ax.grid(True)
self.ax.set_xlabel("Y (meters)")
self.ax.set_ylabel("X (meters)")
self.text.set_text('')
return line,self.text,
#return line,
fig, ax = plt.subplots(1, 1)
plt.gcf().canvas.mpl_connect(
'key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plt.xlabel("Y (meters)")
plt.ylabel("X (meters)")
plt.legend()
ug_i = Update(fig,ax,13)
anim = FuncAnimation(fig, ug_i,init_func=ug_i.init, frames=10, interval=1000, blit=True,repeat=False)
if not show:
writervideo = FFMpegWriter(fps=1)
anim.save('whatever.mp4', writer=writervideo)
print('done')
plt.close()
else:
#plt.legend()
plt.show()
I am new with matplotlib and I am trying to make an animation of a list of grib files.
I wrote this code:
import pygrib
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import os
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
lat_0=0, lon_0=-130)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
for grib in os.listdir("path"):
grbs=pygrib.open(grib)
for grb in grbs:
print grb
lats, lons = grb.latlons()
data=grb.values
x, y = m(lons,lats)
norm=colors.LogNorm())
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
cmap = plt.get_cmap('YlOrBr')
cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
plt.colorbar(cs,orientation='vertical', shrink=0.3)
plt.show()
and it works opening a windows that I have to close and after this opening a new one.
I want to use a nice animation with matplotlib.animation : i would change the grib over a map and showing it as a time series.
I try this:
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
lat_0=0, lon_0=-130)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
#reading the gribs files
griblist = os.listdir("path")
def animate (i):
global griblist
for grib in griblist:
grbs=pygrib.open(grib)
for grb in grbs:
grb
lats, lons = grb.latlons()
x, y = m(lons, lats)
data = grb.values
cmap = plt.get_cmap('YlOrBr')
cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
plt.colorbar(cs,orientation='vertical', shrink=0.5)
plt.title('UV biological effective dose')
anim = animation.FuncAnimation(plt.gcf(), animate,
frames=len(os.listdir("/home/gloria/UV_CAMS")), interval=500, blit=True)
plt.show()
But I got this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 590, in callit
func(*args)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 373, in idle_draw
self.draw()
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 354, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 474, in draw
self.figure.draw(self.renderer)
File "/usr/lib/python2.7/dist-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/figure.py", line 1165, in draw
self.canvas.draw_event(renderer)
File "/usr/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1809, in draw_event
self.callbacks.process(s, event)
File "/usr/lib/python2.7/dist-packages/matplotlib/cbook.py", line 563, in process
proxy(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/cbook.py", line 430, in __call__
return mtd(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 648, in _start
self._init_draw()
File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 1193, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 1214, in _draw_frame
for a in self._drawn_artists:
TypeError: 'NoneType' object is not iterable
What I got if that I need to tell Python to iterate thought some variable using the function animate().
I am not fluent with defining functions and I am stuck in this part of the code: I cannot understand where my code is wrong...
Some help about this?
Many thanks!!
To get rid of the error, set blit=False.
Apart the animation would currently not animate anything because for each frame you loop over all files. Instead you want to show one file per frame.
griblist = os.listdir("path")
def animate (i):
grib = griblist[i]
grbs=pygrib.open(grib)
lats, lons = grb.latlons()
x, y = m(lons, lats)
data = grb.values
cmap = plt.get_cmap('YlOrBr')
cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
plt.colorbar(cs,orientation='vertical', shrink=0.5)
plt.title('UV biological effective dose')
anim = animation.FuncAnimation(plt.gcf(), animate,
frames=len(griblist), interval=500)
plt.show()
I am new to python so I understand that this may be a stupid question, but I am having issues animating this. I can't see what the error is. I get this error
TypeError: f() missing 1 required positional argument: '
I want to use matplotlib when animating, because I have not downloaded scitools.
Any help at all would be very much appriciated
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
x = np.linspace(-6, 6)
tmax = 1
tmin = -1
t = np.linspace(-1, 1)
def f(x, t):
term = (np.exp(-1*(x-3*t)**2))*np.sin(3*np.pi*(x-t))
return term
max_f = f(x[-1], t[-1])
plt.ion()
y = f(x, tmax)
lines = plt.plot(x, y)
plt.axis([x[0], x[-1], -0.1, max_f])
plt.xlabel('x')
plt.ylabel('f')
counter = 0
for ts in t:
y = f(x, t)
lines[0].set_ydata(y)
plt.legend(['ts=%4.2f' % ts])
plt.draw()
plt.savefig('tmp_%04d.png' % counter)
counter += 1
fig = plt.figure()
anim = animation.FuncAnimation(fig, f, interval = 1000, blit=True)
fig = plt.figure()
plt.axis([x[0], x[-1], -0.1, max_f])
lines = plt.plot([], [])
plt.xlabel('x')
plt.ylabel('f')
plt.show()
EDIT, full traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 1699, in call
return self.func(*args)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 745, in callit
func(*args)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 370, in idle_draw
self.draw()
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\figure.py", line 1151, in draw
self.canvas.draw_event(renderer)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backend_bases.py", line 1823, in draw_event
self.callbacks.process(s, event)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook.py", line 554, in process
proxy(*args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook.py", line 416, in call
return mtd(*args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 881, in _start
self._init_draw()
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1540, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1562, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: f() missing 1 required positional argument: 't'
As said, this is not really about the error, you can easily prevent that by supplying some value for t as fargs in FuncAnimation. However, this will not lead to the code producing an animation at all and hence as said, start with the exmaple add your functions and code step by step and see what happens.
This will eventually lead to something like the following:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(-6, 6)
tmax = 1
tmin = -1
t = np.linspace(-1, 1)
def f(x, t):
term = (np.exp(-1*(x-3*t)**2))*np.sin(3*np.pi*(x-t))
return term
y = f(x, tmax)
lines = plt.plot(x, y)
plt.axis([x[0], x[-1], -1, 1])
plt.xlabel('x')
plt.ylabel('f')
counter = [0]
def animate(ts):
y = f(x, ts)
lines[0].set_ydata(y)
plt.legend(['ts=%4.2f' % ts])
#plt.savefig('tmp_%04d.png' % counter)
counter[0] += 1
anim = animation.FuncAnimation(plt.gcf(), animate, frames = t, interval = 1000)
plt.show()
The code is shown below. I am attempting to animate using vectors calculated earlier a figure window is opened so i know it gets this far and the vectors are being calclated correctly. But matplotlib oututs nothing but the figure window I have no idea why. Please help.
#finally animateing
fig = plt.figure()
ax = plt.axes(xlim = (-1000,1000) ,ylim = (-1000,1000))#limits were arbitrary
#line = ax.plot([],[])
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
def animate(i):
x = time_vec[i]
y = complex_vec[i]
#y1 = real_vec[i]
#y2 = modulus_vec[i]
line.set_data(x,y)
#line.set_data(x,y1)
#line.set_data(x,y2)
return line,
animation_object = animation.FuncAnimation(fig, animate, init_func= init, frames = num_files,interval = 30, blit = True)
#turnn this line on to save as mp4
#anim.save("give it a name.mp4", fps = 30, extra-args = ['vcodec', 'libx264'])
plt.show()
THE FULL ERROR MESSAGE IS SHOWN BELOW
Traceback (most recent call last):
File "the_animation.py", line 71, in <module>
plt.show()
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 145, in show
_show(*args, **kw)
File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 117, in __call__
self.mainloop()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 69, in mainloop
Tk.mainloop()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 366, in mainloop
_default_root.tk.mainloop(n)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1484, in __call__
def __call__(self, *args):
MINIMAL EXAMPLE
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
complex_vec = np.arange(5,6,.001)
real_vec = np.arange(7,8,.001)
time_vec = np.arange(0,1,.001)
num_files = np.size(time_vec)
#creating the modulus vector
modulus_vec = np.zeros(np.shape(complex_vec))
for k in range (0,complex_vec.size):
a = complex_vec[k]
b = real_vec[k]
calc_modulus = np.sqrt(a**2 + b**2)
modulus_vec[k] = calc_modulus
#finally animateing
fig = plt.figure()
ax = plt.axes(xlim = (-1000,1000) ,ylim = (-1000,1000))#limits were arbitrary
#line = ax.plot([],[])
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
def animate(i):
x = time_vec[i]
y = complex_vec[i]
y1 = real_vec[i]
y2 = modulus_vec[i]
line.set_data(x,y)
line.set_data(x,y1)
line.set_data(x,y2)
return line,
animation_object = animation.FuncAnimation(fig, animate, init_func= init, frames = num_files,interval = 30, blit = True)
#turnn this line on to save as mp4
#anim.save("give it a name.mp4", fps = 30, extra-args = ['vcodec', 'libx264'])
plt.show()
The problem here is in your animate function, you're using set_data multiple times which does not do what you think it does. You're using it like an append, when it's a set. The arguments should be two arrays, containing the respective x and y values for that line. This will animate your minimal example:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
complex_vec = np.arange(5,6,.001)
real_vec = np.arange(7,8,.001)
time_vec = np.arange(0,1,.001)
num_files = np.size(time_vec)
#creating the modulus vector
modulus_vec = np.zeros(np.shape(complex_vec))
for k in range (0,complex_vec.size):
a = complex_vec[k]
b = real_vec[k]
calc_modulus = np.sqrt(a**2 + b**2)
modulus_vec[k] = calc_modulus
#finally animateing
fig = plt.figure()
ax = plt.axes(xlim = (-1,1) ,ylim = (-1,15))#limits were arbitrary
#line = ax.plot([],[])
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
def animate(i):
x = time_vec[i]
y = complex_vec[i]
y1 = real_vec[i]
y2 = modulus_vec[i]
# notice we are only calling set_data once, and bundling the y values into an array
line.set_data(x,np.array([y, y1, y2]))
return line,
animation_object = animation.FuncAnimation(fig,
animate,
init_func= init,
frames = num_files,
interval = 30,
blit = True)
#turnn this line on to save as mp4
#anim.save("give it a name.mp4", fps = 30, extra-args = ['vcodec', 'libx264'])
plt.show()
Your previous attempt was setting the x and y values, then overwriting the previous with a new x and y, then doing that once again.
I am writing a program in Python, using matplotlib to (among other things) run an animation showing a numerical solution to the time-dependent Schrodinger Equation.
Everything is working fine, but once an animation has finished running, I would like the window it was in to close itself. My way of doing this (shown below) works, but exceptions are thrown up which I cant seem to catch. It works fine for what I need it to do, but the error looks very messy.
I have an alternative method which works without throwing an error, but requires the user to manually close the window (unacceptable for my purposes). Can someone please point out what I am doing wrong, or suggest a better option?
A simplified version of the relevant parts of my code follows:
from matplotlib import animation as ani
from matplotlib import pyplot as plt
multiplier = 0
def get_data(): # some dummy data to animate
x = range(-10, 11)
global multiplier
y = [multiplier * i for i in x]
multiplier += 0.005
return x, y
class Schrodinger_Solver(object):
def __init__(self, xlim = (-10, 10), ylim = (-10, 10), num_frames = 200):
self.num_frames = num_frames
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111, xlim = xlim, ylim = ylim)
self.p_line, = self.ax.plot([], [])
self.ani = ani.FuncAnimation(self.fig, self.animate_frame,
init_func = self.init_func,
interval = 1, frames = self.num_frames,
repeat = False, blit = True)
plt.show()
def animate_frame(self, framenum):
data = get_data()
self.p_line.set_data(data[0], data[1])
if framenum == self.num_frames - 1:
plt.close()
# closes the window when the last frame is reached,
# but exception is thrown. Comment out to avoid the error,
# but then the window needs manual closing
return self.p_line,
def init_func(self):
self.p_line.set_data([], [])
return self.p_line,
Schrodinger_Solver()
I am running Python 2.7.2 on windows 7, with matplotlib 1.1.0
Thanks in advance
EDIT:
exception and traceback as follows:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 495, in callit
func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 116, in _on_timer
TimerBase._on_timer(self)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1092, in _on_timer
ret = func(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 315, in _step
still_going = Animation._step(self, *args)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 177, in _step
self._draw_next_frame(framedata, self._blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 197, in _draw_next_frame
self._post_draw(framedata, blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 220, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 240, in _blit_draw
ax.figure.canvas.blit(ax.bbox)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 244, in blit
tkagg.blit(self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2)
File "C:\Python27\lib\site-packages\matplotlib\backends\tkagg.py", line 19, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
TclError: this isn't a Tk application
Traceback (most recent call last):
File "C:\Python27\quicktest.py", line 44, in <module>
Schrodinger_Solver()
File "C:\Python27\quicktest.py", line 26, in __init__
plt.show()
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 139, in show
_show(*args, **kw)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 109, in __call__
self.mainloop()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 69, in mainloop
Tk.mainloop()
File "C:\Python27\lib\lib-tk\Tkinter.py", line 325, in mainloop
_default_root.tk.mainloop(n)
AttributeError: 'NoneType' object has no attribute 'tk'
I can catch the second exception, the AttributeError, by a small change:
try: plt.show()
except AttributeError: pass
but the first part, the TclError, remains no matter what I try
I had the same problem a few minutes before... The reason was a very low interval-value in FuncAnimation. Your code tries to update the graphics evere 1 millisecond - quite fast! (1000 fps might not be needed). I tried interval=200 and the error was gone...
HTH
try with:
if framenum == self.num_frames - 1:
exit()
it works for me...
I am facing the exact same problem, and I managed to solve the issue by creating another Animation class. Essentially, I made two changes:
Write a custom class that overwrites the _stop and _step methods.
Riase an StopIteration error in the update function, instead of using plt.close. The exception will be caught and won't break the script.
Here is the code.
from matplotlib import animation as ani
from matplotlib import pyplot as plt
class FuncAnimationDisposable(ani.FuncAnimation):
def __init__(self, fig, func, **kwargs):
super().__init__(fig, func, **kwargs)
def _step(self, *args):
still_going = ani.Animation._step(self, *args)
if not still_going and self.repeat:
super()._init_draw()
self.frame_seq = self.new_frame_seq()
self.event_source.interval = self._repeat_delay
return True
elif (not still_going) and (not self.repeat):
plt.close() # this code stopped the window
return False
else:
self.event_source.interval = self._interval
return still_going
def _stop(self, *args):
# On stop we disconnect all of our events.
if self._blit:
self._fig.canvas.mpl_disconnect(self._resize_id)
self._fig.canvas.mpl_disconnect(self._close_id)
multiplier = 0
def get_data(): # some dummy data to animate
x = range(-10, 11)
global multiplier
y = [multiplier * i for i in x]
multiplier += 0.005
return x, y
class Schrodinger_Solver(object):
def __init__(self, xlim = (-10, 10), ylim = (-10, 10), num_frames = 200):
self.num_frames = num_frames
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111, xlim = xlim, ylim = ylim)
self.p_line, = self.ax.plot([], [])
self.ani = FuncAnimationDisposable(self.fig, self.animate_frame,
init_func = self.init_func,
interval = 1, frames = self.num_frames,
repeat = False, blit = True)
plt.show()
def animate_frame(self, framenum):
data = get_data()
self.p_line.set_data(data[0], data[1])
if framenum == self.num_frames - 1:
raise StopIteration # instead of plt.close()
return self.p_line,
def init_func(self):
self.p_line.set_data([], [])
return self.p_line,
Schrodinger_Solver()
Schrodinger_Solver()
print(multiplier)
(The code snippet was tested with Python 3.7 and matplotlib 3.4.2.)