【问题标题】:Animation not animated in matplotlib动画在 matplotlib 中没有动画
【发布时间】:2015-01-04 16:38:04
【问题描述】:

我正在设计一个模拟查看器,其中使用 matplotlib 中的 FuncAnimation 对点进行动画处理。

这是我目前所拥有的(后面会用到VX、VY、M、t_lim)。它只会产生一个空白的情节,没有任何动作。

我从here 的第一个示例中复制了一些内容。

这真的很简单(字面意思是两个点在一个时间步中聚集在一起),为什么这不起作用?

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

class visualisation(object):
    def __init__(self, X, Y, VX, VY, M, t_lim=None):
        self.X = X
        self.Y = Y
        self.VX = VX
        self.VY = VY
        self.M = M
        self.t_lim = t_lim

        self.fig = plt.figure()
        addx = (X.max() - X.min()) * 0.05
        addy = (Y.max() - Y.min()) * 0.05
        self.ax = plt.axes(xlim=(X.min()-addx, X.max()+addx), ylim=(Y.min()-addy, Y.max()+addy))
        self.points, = self.ax.plot([], [], 'b.', ms=10)

    def init(self):
        self.points.set_data([], [])
        return self.points,

    def animator(self, i):
        print self.X[:,i]
        self.points.set_data(self.X[:,i], self.Y[:,i])
        return self.points,

    def animate(self):
        return animation.FuncAnimation(self.fig, self.animator, init_func=self.init, frames=200, interval=20, blit=True)


M_sun = 2.99e30
N = 1000

ms = np.array([1., 1.]) * M_sun

#initial conditions
xs = np.zeros([len(ms), N]) #[n, t]
xs[:, 0] = [0, 1]

ys = np.zeros([len(ms), N]) #[n, t]
ys[:, 0] = [0, 1]

vxs, vys = (np.zeros_like(xs))*2

visual = visualisation(xs, ys, vxs, vys, ms)
visual.animate()

plt.show()

【问题讨论】:

    标签: python animation matplotlib


    【解决方案1】:

    您必须保存您在animate(self) 中创建的FuncAnimation 对象。否则会在调用plt.show() 之前被垃圾回收:

    amin = visual.animate()
    

    或:

    def animate(self):
        self.anim = animation.FuncAnimation(self.fig, self.animator, 
                init_func=self.init, frames=200, interval=20, blit=True)
    

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2017-05-24
      • 2021-07-03
      相关资源
      最近更新 更多