matplotlib exit after animation - python

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.)

Related

Python Matplotlib show the cursor when hovering on graph

I want to plot the close price of INS as below and it works. Then I want to add the cursor when hovering on the graph. I follow the demo from https://matplotlib.org/3.1.0/gallery/misc/cursor_demo_sgskip.html and that is what I want.
But when I added these lines into the code, it shows value error. Initially I use epoch time as x-axis and I thought that is the problem, so I convert epoch time to datetime but it is still not working and plot nothing.
snap_cursor = SnaptoCursor(ax, secs, df['close'])
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.mouse_move)
Traceback (most recent call last): File
"c:\Users\Sam.vscode\extensions\ms-python.python-2020.6.89148\pythonFiles\ptvsd_launcher.py",
line 48, in
main(ptvsdArgs) File "c:\Users\Sam.vscode\extensions\ms-python.python-2020.6.89148\pythonFiles\lib\python\old_ptvsd\ptvsd_main_.py",
line 432, in main
run() File "c:\Users\Sam.vscode\extensions\ms-python.python-2020.6.89148\pythonFiles\lib\python\old_ptvsd\ptvsd_main_.py",
line 316, in run_file
runpy.run_path(target, run_name='main') File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\runpy.py",
line 263, in run_path
pkg_name=pkg_name, script_name=fname) File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\runpy.py",
line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name) File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\runpy.py",
line 85, in _run_code
exec(code, run_globals) File "c:\Users\Sam\OneDrive\Project\stock\test.py", line 89, in
plt.gcf().autofmt_xdate() File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\figure.py",
line 632, in autofmt_xdate
for label in self.axes[0].get_xticklabels(which=which): File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axes_base.py",
line 3355, in get_xticklabels
return self.xaxis.get_ticklabels(minor=minor, which=which) File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axis.py",
line 1320, in get_ticklabels
return self.get_majorticklabels() File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axis.py",
line 1276, in get_majorticklabels File
"C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axis.py",
line 1431, in get_major_ticks
numticks = len(self.get_majorticklocs()) File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axis.py",
line 1348, in get_majorticklocs
return self.major.locator() File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\dates.py",
line 1338, in call
self.refresh() File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\dates.py",
line 1364, in refresh
dmin, dmax = self.viewlim_to_dt() File "C:\Users\Sam\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\dates.py",
line 1098, in viewlim_to_dt
.format(vmin))
ValueError: view limit minimum -36879.777083333334 is less than 1 and
is an invalid Matplotlib date value. This often happens if you pass a
non-datetime value to an axis that has datetime units
class SnaptoCursor(object):
"""
Like Cursor but the crosshair snaps to the nearest x, y point.
For simplicity, this assumes that *x* is sorted.
"""
def __init__(self, ax, x, y):
self.ax = ax
self.lx = ax.axhline(color='k') # the horiz line
self.ly = ax.axvline(color='k') # the vert line
self.x = x
self.y = y
# text location in axes coords
self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
indx = min(np.searchsorted(self.x, x), len(self.x) - 1)
x = self.x[indx]
y = self.y[indx]
# update the line positions
self.lx.set_ydata(y)
self.ly.set_xdata(x)
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
print('x=%1.2f, y=%1.2f' % (x, y))
self.ax.figure.canvas.draw()
data = td.pricehistory("INS")
df = pd.DataFrame(data['candles'])
df['datetime'] = df.apply(lambda x: datetime.datetime.fromtimestamp(x['datetime']/1000),axis=1)
secs = df['datetime']
fig, ax = plt.subplots(1, 1)
ax.plot(secs,df['close'])
snap_cursor = SnaptoCursor(ax, secs, df['close'])
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.mouse_move)
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%d-%m-%y %H:%M:%S')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.show()
I'm not familiar with SnaptoCursor, but have you considered using plotly instead?
Saves many lines of code and is very user-friendly:
# install plotly library
!pip install plotly
# import express module
import plotly.express as px
# plot interactive line chart
fig = px.line(data=df, x="datetime", y="close")
fig.show()
It's very flexible too. Here is the documentation: https://plotly.com/python/line-charts/
You can interact with the plots using the cursor too, for example:
Hope this helps, though of course it's different to what you were trying to do!

Python, animate a function with two arguments

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()

Intermittent error while plotting graph using matplotlib "RuntimeError: main thread is not in main loop"

I am trying to pull data from different end points using my python code and feeding the same data to plot a graph using matplotlib. I dont have any problem in reading the data but when i invoke the methods to plot graph by feeding the data i see intermittent error caused by matplot lib. below are the error details.
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\slackbot\dispatcher.py", line 55, in _dispatch_msg_handler
func(Message(self._client, msg), *args)
File "C:\PycharmProjects\SlackBot\src\plugins\bot_response.py", line 248, in checkmarx
draw_chart.riskscore_bar(top_riskscore, project_name, "output_files", "riskscore_bar.png")
File "C:\PycharmProjects\SlackBot\src\drawchart.py", line 111, in riskscore_bar
fig, ax = plt.subplots()
File "C:\Python35\lib\site-packages\matplotlib\pyplot.py", line 1202, in subplots
fig = figure(**fig_kw)
File "C:\Python35\lib\site-packages\matplotlib\pyplot.py", line 535, in figure
**kwargs)
File "C:\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 81, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "C:\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 98, in new_figure_manager_given_figure
icon_img = Tk.PhotoImage(file=icon_fname)
File "C:\Python35\lib\tkinter\__init__.py", line 3403, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python35\lib\tkinter\__init__.py", line 3359, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
RuntimeError: main thread is not in main loop
I have tried looking into other cases from stackoverflow with same error messages, but it didnt help me fix this. Below is my code snippet that invokes an error.
def riskscore_bar(self, top_riskscore, project_id, output_folder, output_filename):
logger.debug("Inside method plotgraph in drawchart.py.")
y_pos = np.arange(len(project_id))
width = .4
fig, ax = plt.subplots()
graph = ax.bar(y_pos+1, top_riskscore, width, color='#feb308')
ax.set_ylabel('Risk Score')
ax.set_title('Summary')
ax.set_xticks(y_pos + 1)
ax.set_xticklabels(project_id,fontsize=5, rotation=45 )
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.001*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(graph)
pylab.savefig(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', output_folder,output_filename))
The error seems to occur at "fig, ax = plt.subplots()". any ideas on how this can be fixed?
this can be solved by adding plt.switch_backend('agg') below right after you import matplotlib.pyplot as plt. As shown below
import matplotlib.pyplot as plt
plt.switch_backend('agg')

Matplotlib FuncAnimation, error when blit = true.

I am trying to make an animation of an expanding circle using FuncAnimation and circle.set_radius(). However, the animation only works when blit = False. The code is as follow:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig, ax = plt.subplots()
plt.grid(True)
plt.axis([-0.6, 0.6, -0.6, 0.6])
circle1= plt.Circle([0,0],0.01,color="0.",fill=False, clip_on = True)
ax.add_patch(circle1)
dt = 1.0/20
vel = 0.1
def init():
circle1.set_radius(0.01)
def animate(i):
global dt, vel
r = vel * i * dt
circle1.set_radius(r)
return circle1,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval= 50, blit=True)
It returns this error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1139, in draw
self.canvas.draw_event(renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1809, in draw_event
self.callbacks.process(s, event)
File "/usr/local/lib/python2.7/site-packages/matplotlib/cbook.py", line 562, in process
proxy(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/cbook.py", line 429, in __call__
return mtd(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/animation.py", line 620, in _start
self._init_draw()
File "/usr/local/lib/python2.7/site-packages/matplotlib/animation.py", line 1166, in _init_draw
for a in self._drawn_artists:
TypeError: 'NoneType' object is not utterable
I am using mac OS. The animation will work when I changed blit = False. However, whenever I move my mouse there animation slow down. This is problematic because I have a separate thread generating the sound output. In practice, the circle will hit some data points and make sound. As a result they are not in sync. Please help.
From the docs,
If blit=True, func and init_func should return an iterable of drawables to clear.
Therefore - you need to add return circle1, to your function init(). The other option is not to specify an init_func at all in your call to FuncAnimation - you may not need it. The animations probably does what you want without it.
NOTE the trailing comma after circle1 - this means a (1 element) tuple is returned, so that the return value is iterable as required. You already have this in the animate function.

Matplotlib animating multiple lines and text

Thanks for taking time to read my question, first time I have posted on SO so here goes...
I am plotting time series data in an animation using matplotlib.animation.FuncAnimation
I am plotting more than one line by looping over a list and slicing data from a numpy array.
This works fine, but I also want to add text to the plot which is animated and describes the frame number.
I have included sample code below.
I am trying returning a list of line objects and a text object from the animate function.
I receive an attribute error when I try to do this:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 531, in callit
func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 141, in _on_timer
TimerBase._on_timer(self)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1117, in _on_timer
ret = func(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 773, in _step
still_going = Animation._step(self, *args)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 632, in _step
self._draw_next_frame(framedata, self._blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 652, in _draw_next_frame
self._post_draw(framedata, blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 675, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 688, in _blit_draw
if a.axes not in bg_cache:
AttributeError: 'list' object has no attribute 'axes'
But, say that I have a list of two line objects, if I return the objects individually, e.g.
return lines[0],lines[1], timetext
I receive no errors.
Any ideas?
Cheers
Vanessa
import numpy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
npdata = numpy.random.randint(100, size=(5,6,10))
plotlays, plotcols = [2,5], ["black","red"]
fig = plt.figure()
ax = plt.axes(xlim=(0, numpy.shape(npdata)[0]), ylim=(0, numpy.max(npdata)))
timetext = ax.text(0.5,50,'')
lines = []
for index,lay in enumerate(plotlays):
lobj = ax.plot([],[],lw=2,color=plotcols[index])[0]
lines.append(lobj)
def init():
for line in lines:
line.set_data([],[])
return lines
def animate(i):
timetext.set_text(i)
x = numpy.array(range(1,npdata.shape[0]+1))
for lnum,line in enumerate(lines):
line.set_data(x,npdata[:,plotlays[lnum]-1,i])
return lines, timetext
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=numpy.shape(npdata)[1], interval=100, blit=True)
plt.show()
def animate(i):
timetext.set_text(i)
x = numpy.array(range(1,npdata.shape[0]+1))
for lnum,line in enumerate(lines):
line.set_data(x,npdata[:,plotlays[lnum]-1,i])
return lines, timetext # <- returns a tuple of form (list, artist)
change this to
return tuple(lines) + (timetext,)
or something similar so that you return an iterable of artists from animate.

Categories