简体   繁体   中英

matplotlib animation does not update when in wxpython gui but works standalone

I have a wxPython GUI in which I use matplotlib for 2D and 3D graphics.

I was having problems getting a surface plot to animate, so I used the following dummy case adapted from someplace online to test. It is a fairly typical example for 3D animation and works fine when run standalone.

if True:
  from mpl_toolkits.mplot3d import axes3d
  import numpy as np
  import matplotlib.pyplot as plt
  import matplotlib.animation as animation
  def generate(X, Y, phi):
    R = 1 - np.sqrt(X**2 + Y**2)
    return np.cos(2 * np.pi * X + phi) * R

  fig = plt.figure()
  ax = axes3d.Axes3D(fig)

  xs = np.linspace(-1, 1, 3)
  ys = np.linspace(-1, 1, 3)
  X, Y = np.meshgrid(xs, ys)
  Z = generate(X, Y, 0.0)
  wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
  ax.set_zlim(-1,1)

  def update(i, ax, fig):
    print i
    ax.cla()
    phi = i * 360 / 2 / np.pi / 100
    Z = generate(X, Y, phi)
    wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
    ax.set_zlim(-1,1)
    return wframe

  ani = animation.FuncAnimation(fig, update, 
      frames=xrange(100), 
      fargs=(ax, fig), interval=100)
plt.show()

The "True" test is of course unnecessary but was meant to replicate something like the structure in the GUI at the point of execution (to check for any scoping issues).

When I insert the exact same code into my GUI with a wx.Button causing execution of the code, it plots only the first frame and nothing else, but doesn't issue any error either (running inside IDLE). I can verify by printing that exactly one (the first iteration i=0 ) frame is plotting.

This is exactly the behavior also of the actual data of interest which originated the problem.

Thank you.

When using an animation inside of a GUI class, make sure to keep the reference to the animation object in a class member so that it doesn't get garbage collected at the end of the method in which it is created. Using something like

self.ani = animation.FuncAnimation(....

rather than

ani = animation.FuncAnimation(....

should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM