Home > Enterprise >  Making an Animation with Matplotlib
Making an Animation with Matplotlib

Time:12-21

I am trying to create an animation in Python with MatPlotLib. But, I don't know what is wrong with my following code. It is producing a blank image.

from matplotlib import pyplot as plt
import matplotlib.animation as animation

domain = [0., 1., 2.]
images = [[0., 0., 0.],
          [1., 1., 1.],
          [2., 2., 2.]]

figure = plt.figure()
axes = plt.axes()
graph = axes.plot([])
def set_frame(image):
    graph.set_data(domain, image)
    return graph
animation.FuncAnimation(figure, set_frame, frames=images)
plt.ylim(0., 2.)
plt.show()

CodePudding user response:

  1. You need to assign animation to a variable to prevent it from being deleted

  2. graph is a list you need to retrieve an element

from matplotlib import pyplot as plt
import matplotlib.animation as animation

domain = [0., 1., 2.]
images = [[0., 0., 0.],
          [1., 1., 1.],
          [2., 2., 2.]]

figure = plt.figure()
axes = plt.axes()
graph = axes.plot([])
def set_frame(image):
    graph[0].set_data(domain, image)
    return graph
_ = animation.FuncAnimation(figure, set_frame, frames=images)
plt.ylim(0., 2.)
plt.show()
  • Related