5

I have a matrix which is time-depedent and I want to plot the evolution as an Animation.

My code is the following:

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

However, when I run it I always obtain the following error: draw_artist can only be used after an initial draw which caches the render. I don't know where this error come from and no idea on how to solve it. I have read this answer and also this article but still don't know why my code is not working.

Any help is appreciated, thank you!

Community
  • 1
  • 1
Victor Buendía
  • 451
  • 11
  • 21

1 Answers1

5

You're very close to a working solution. Either change

plot = plt.matshow(data[0])

to

plot = plt.matshow(data[0], fignum=0)

or use

plot = plt.imshow(data[0])

instead.


The problem with using plt.matshow(data[0]) here is that it creates a new figure if the fignum parameter is left blank (i.e. equal to None by default). Since fig = plt.figure() is called and that fig is passed to FuncAnimation, you end up with two figures, one with the result of plt.matshow, and the other blank one being drawn on by FuncAnimation. The figure that FuncAnimation is drawing on does not find the initial draw, so it raises

AttributeError: draw_artist can only be used after an initial draw which caches the render
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677