Animate matshow function in matplotlib
<p>I have a matrix which is time-depedent and I want to plot the evolution as an Animation. </p>

<p>My code is the following:</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt
from  matplotlib.animation import FuncAnimation


n_frames = 3 #Numero de ficheros que hemos generado
data = np.empty(n_frames, dtype=object) #Almacena los datos

#Leer todos los datos
for k in range(n_frames):
    data[k] = np.loadtxt("frame"+str(k))


fig = plt.figure()
plot =plt.matshow(data[0])

def init():
    plot.set_data(data[0])
    return plot

def update(j):
    plot.set_data(data[j])
    return [plot]


anim = FuncAnimation(fig, update, init_func = init, frames=n_frames, interval = 30, blit=True)

plt.show()
</code></pre>

<p>However, when I run it I always obtain the following error: <code>draw_artist can only be used after an initial draw which caches the render</code>. I don't know where this error come from and no idea on how to solve it. 
I have read <a href="http://stackoverflow.com/questions/10429556/animate-quadratic-grid-changes-matshow">this answer</a> and also <a href="https://datasciencelab.wordpress.com/tag/matplotlib/" rel="nofollow">this article</a> but still don't know why my code is not working.</p>

<p>Any help is appreciated, thank you!</p>

<p>You're very close to a working solution. Either change</p>

<pre><code>plot = plt.matshow(data[0])
</code></pre>

<p>to</p>

<pre><code>plot = plt.matshow(data[0], fignum=0)
</code></pre>

<p>or use</p>

<pre><code>plot = plt.imshow(data[0])
</code></pre>

<p>instead.</p>

<hr>

<p>The problem with using <code>plt.matshow(data[0])</code> here is that it <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/pyplot.py#L2241" rel="nofollow">creates a new figure</a> if the <code>fignum</code> parameter is left blank (i.e. equal to <code>None</code> by default). 
Since <code>fig = plt.figure()</code> is called and that <code>fig</code> is passed to <code>FuncAnimation</code>, you end up with two figures, one with the result of <code>plt.matshow</code>, and the other blank one being drawn on by <code>FuncAnimation</code>. The figure that <code>FuncAnimation</code> is drawing on does not find the initial draw, so it raises</p>

<pre><code>AttributeError: draw_artist can only be used after an initial draw which caches the render
</code></pre>

python animation matplotlib