2
votes

I was trying to use matplotlib to replot an image in a faster way, so instead of replotting everything, I use set_data method of the AxesImage class as below:

import numpy as np
import time
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
img = plt.imshow(np.random.rand(100, 100))

img.set_data(np.random.rand(100, 100))
ax.draw_artist(ax.patch)
ax.draw_artist(img)
fig.canvas.update()
fig.canvas.flush_events()

I encountered this error:

Traceback (most recent call last): ... ax.draw_artist(ax.patch) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_base.py", line 2319, in draw_artist raise AttributeError(msg) AttributeError: draw_artist can only be used after an initial draw which caches the render

However, if I run the script line by line in python shell (IPython), it works and nothing is wrong. So what is the mystery behind this cached renderer?

EDIT: add a line fig.canvas.draw() solves the problem, now the remaining question is why running it line by line in IPython shell does not cause the same error?

1
You should also look into blitting. - tacaswell
@tcaswell according to the post at bastibe.de/2013-05-30-speeding-up-matplotlib.html, blit causes memory leak... - shelper
That is a very old article. It may have been fixed already and if not should be reported upstream as a bug. - tacaswell

1 Answers

3
votes

As you figured out, it is necessary to draw the canvas at least once in order to cache the renderer before you can call draw_artist:

draw_artist(a)

This method can only be used after an initial draw which caches the renderer. It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)


I'm guessing that in your IPython session you are running matplotlib in interactive mode, in which case your initial call to plt.subplots will immediately cause the canvas of the new figure to be drawn and the renderer to be cached.

To replicate the AttributeError you are seeing in your script, you could turn off interactive mode using plt.ioff():

In [1]: plt.ioff()

In [2]: fig, ax = plt.subplots(1, 1)

In [3]: img = plt.imshow(np.random.rand(100, 100))

In [4]: img.set_data(np.random.rand(100, 100))

In [5]: ax.draw_artist(ax.patch)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-b54815e41caa> in <module>()
----> 1 ax.draw_artist(ax.patch)

/home/alistair/.venvs/core/local/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in draw_artist(self, a)
   2317             msg = ('draw_artist can only be used after an initial draw which'
   2318                    ' caches the render')
-> 2319             raise AttributeError(msg)
   2320         a.draw(self._cachedRenderer)
   2321 

AttributeError: draw_artist can only be used after an initial draw which caches the render