Matplotlib animating multiple lines and text - python

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.

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!

Tkinter outputting KeyError when Updating Multiple Matplotlib Objects

I am somewhat new to python animation, and I'm getting the following error when I try to update multiple matplotlib 2D objects in FuncAnimation
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/me/anaconda/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "/Users/me/anaconda/lib/python3.6/tkinter/__init__.py", line 745, in callit
func(*args)
File "/Users/me/anaconda/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py", line 95, in _on_timer
TimerBase._on_timer(self)
File "/Users/me/anaconda/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 1382, in _on_timer
ret = func(*args, **kwargs)
File "/Users/me/anaconda/lib/python3.6/site-packages/matplotlib/animation.py", line 1542, in _step
still_going = Animation._step(self, *args)
File "/Users/me/anaconda/lib/python3.6/site-packages/matplotlib/animation.py", line 1277, in _step
self._draw_next_frame(framedata, self._blit)
File "/Users/me/anaconda/lib/python3.6/site-packages/matplotlib/animation.py", line 1296, in _draw_next_frame
self._draw_frame(framedata)
File "/Users/me/anaconda/lib/python3.6/site-packages/matplotlib/animation.py", line 1814, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
File "<ipython-input-73-4c78ddeac2f8>", line 10, in animate
moving_x = [0, orbradii[ii]*np.cos(angle)]
File "/Users/me/anaconda/lib/python3.6/site-packages/pandas/core/series.py", line 623, in __getitem__
result = self.index.get_value(self, key)
File "/Users/me/anaconda/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2557, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 817, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 0
Following is the code that I wrote to animate orbital motion. I have been running this in python 3.6 using TkAgg as the backend.
df = pd.read_csv('file.csv')
orbradii = df['radii']
planet_total = len(orbradii)
fig = plt.figure()
ax = fig.add_subplot(111, xlim=(-max(orbradii), max(orbradii)), ylim=(-max(orb_radii), max(orb_radii)))
lines = []
for _ in range(planet_total):
lines.append(ax.plot([], [], 'o'))
def init():
#set the data to empty lists for the x, y coordinates, respectively
for ii in range(len(lines)):
print(lines[ii])
lines[ii][0].set_data([], [])
return lines
def animate(i):
angle = i/10. * np.pi
for ii in range(planet_total):
moving_x = [0, orbradii[ii]*np.cos(angle)]
moving_y = [0, orbradii[ii]*np.sin(angle)]
#set the x, y coordinates to these new values
print(lines[ii])
lines[ii][0].set_data(moving_x, moving_y)
return lines
our_animation = ani.FuncAnimation(fig, animate, np.arange(1, 1000), interval=75, init_func=init)
plt.show()
Thank you for your help!
EDIT:
Thanks to Tom's comment, I realized that if I convert the orbradii variable to values, my code works.
orbradii = df['radii'].values

python cluster animation using matplotlib and different colors

I'm trying to create an animation of my clustering where each cluster is a different color on a scatter plot and there are several clusters per plot. The next plot to show has the same clusters and colors but a different location.
I've searched around and so far have this (timePeriodData refers to a list of cluster objects. Each list contains the clusters for that time/plot and the cluster object has the x, y, and color data.):
plt.ion()
fig,ax = subplots(1,1)
ax.set_aspect('equal')
fig.canvas.draw()
background = fig.canvas.copy_from_bbox(ax.bbox)
for timeData in timePeriodData:
plt.clf()
#print timeperiod
for cluster in timeData:
#ax.scatter(cluster.dataX,cluster.dataY, color = cluster.color)
# restore background
plt.scatter(cluster.dataX,cluster.dataY, color = cluster.color)
#plt.show()
#fig.canvas.restore_region(background)
# redraw just the points
#ax.draw_artist()
# fill in the axes rectangle
#fig.canvas.blit(ax.bbox)
plt.draw()
time.sleep(1)
But the plot window eventually hangs and doesn't continue plotting after about 5 plots. You can see in the comments I also tried to save the background and update that, but I am doing something wrong there. What exactly needs to be updated confuses me and I can't find good documentation on what needs to be passed to draw_artist.
I've also tried to use the animation feature of matplotlib, but can't seem to get it working with what I am trying to do.
timeperiods = 4
fig, ax = plt.subplots()
#fig = plt.figure()
def update(timePeriod, *args):
clusterNum = 0
for cluster in args[timePeriod]:
scat = ax.scatter(cluster.dataX,cluster.dataY, color = cluster.color)
clusterNum +=1
#scat = ax.scatter(dataX, dataY, c = scalarMap.to_rgba(values[clusterNum]))
return scat
ani = animation.FuncAnimation(fig, update, frames=xrange(timeperiods),
fargs=(timePeriodData), blit = True)
plt.show()
It says something is not iterable, but I'm sure what part it is referring to. I'm also not sure if I can continually assign scat to ax.scatter and it will add the points or not. but I assume so. Error message is:
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\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1040, in draw
self.canvas.draw_event(renderer)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1693, in draw_event
self.callbacks.process(s, event)
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 527, in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 405, in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 832, in _end_redraw
self._post_draw(None, self._blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 778, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 787, in _blit_draw
for a in artists:
TypeError: 'PathCollection' object is not iterable
Any help getting a working system would be great!

matplotlib exit after animation

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

How to get rid of maximum recursion depth error while plotting interactively?

I'm trying to build an interactive plot. This one is supposed to clear the figure if clicked within axes and draw a circle at a random place. The code is as follows:
import matplotlib.pyplot as plt
import random
def draw_circle(event):
if event.inaxes:
print(event.xdata, event.ydata)
plt.cla()
a = random.randint(0,100)
b = random.randint(0,100)
s, = plt.plot(a,b,'o', ms=100, color="blue",visible=True )
plt.show()
fig = plt.figure()
ax = plt.subplot(111)
s, = plt.plot(1,2,'o', ms=100, color="blue",visible=True )
plt.connect("button_press_event", draw_circle)
plt.show()
After clicking for 42 times, the program breaks and I get the following traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 286, in button_press_event
FigureCanvasBase.button_press_event(self, x, y, num, guiEvent=event)
File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1632, in button_press_event
self.callbacks.process(s, mouseevent)
File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 262, in process
proxy(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 192, in __call__
return mtd(*args, **kwargs)
File "/home/almarahat/Dropbox/python/GUI/Testing site/test_rt/baud_test.py", line 8, in draw_circle
plt.cla()
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2784, in cla
ret = gca().cla()
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 842, in cla
spine.cla()
File "/usr/lib/pymodules/python2.7/matplotlib/spines.py", line 157, in cla
self.axis.cla()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 731, in cla
self.reset_ticks()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 744, in reset_ticks
self.majorTicks.extend([self._get_tick(major=True)])
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 1553, in _get_tick
return XTick(self.axes, 0, '', major=major, **tick_kw)
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 141, in __init__
self.tick2line = self._get_tick2line()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 401, in _get_tick2line
l.set_transform(self.axes.get_xaxis_transform(which='tick2'))
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 586, in get_xaxis_transform
return self.spines['top'].get_spine_transform()
File "/usr/lib/pymodules/python2.7/matplotlib/spines.py", line 374, in get_spine_transform
self._ensure_position_is_set()
File "/usr/lib/pymodules/python2.7/matplotlib/spines.py", line 140, in _ensure_position_is_set
self.set_position(self._position)
File "/usr/lib/pymodules/python2.7/matplotlib/spines.py", line 365, in set_position
self.axis.cla()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 731, in cla
self.reset_ticks()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 744, in reset_ticks
self.majorTicks.extend([self._get_tick(major=True)])
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 1553, in _get_tick
return XTick(self.axes, 0, '', major=major, **tick_kw)
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 140, in __init__
self.tick1line = self._get_tick1line()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 383, in _get_tick1line
zorder=self._zorder,
File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 195, in __init__
self._marker = MarkerStyle()
File "/usr/lib/pymodules/python2.7/matplotlib/markers.py", line 112, in __init__
self.set_marker(marker)
File "/usr/lib/pymodules/python2.7/matplotlib/markers.py", line 171, in set_marker
self._recache()
File "/usr/lib/pymodules/python2.7/matplotlib/markers.py", line 116, in _recache
self._path = Path(np.empty((0,2)))
File "/usr/lib/pymodules/python2.7/matplotlib/path.py", line 112, in __init__
if ma.isMaskedArray(vertices):
File "/usr/local/lib/python2.7/dist-packages/numpy-1.6.2-py2.7-linux-x86_64.egg/numpy/ma/core.py", line 5683, in isMaskedArray
return isinstance(x, MaskedArray)
RuntimeError: maximum recursion depth exceeded while calling a Python object
At this point, I am not certain where the recursion occurs and how to alleviate this error.
I understand (from other Q&As) that I could enhance my stack limit and get around the problem. However, I don't consider that as a solution in this particular case and would like to get to the bottom of this.
Any help would be appreciate.
Thanks in advance.
Additional Information:
The main functionality that matters include clearing the figure and drawing something new on clicking the canvas.
The clicking does not raise this error, if I am not trying to plot something. Thus, I suspect, I'm missing something in handling matplotlib.
Instead of plt.show(), from within your callback call plt.draw(). The problem is that plt.show runs a mainloop of the GUI library; you just want to update what is shown within the existing mainloop. Using the Qt backend, your code would show the error QCoreApplication::exec: The event loop is already running.
See What is interactive mode? for more guidance on how to use Matplotlib interactively.

Categories