Matplotlib动画实时

时间:2015-11-03 21:05:22

标签: python performance animation matplotlib

在下面的示例中,我想制作一个动画,其中一个点在T秒内绕圆圈移动(例如T = 10)。但是它慢了很多而且不起作用。那么,我的代码有什么问题以及如何修复它?据我所知,api(http://matplotlib.org/api/animation_api.html)设置interval=1应该每毫秒更新一次数字。

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

R = 3
T = 10

fig = plt.figure()
fig.set_dpi(300)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(-10, 10), ylim=(-R*1.5, R*1.5))
ax.set_aspect('equal')


patch = plt.Circle((0, 0), 0.1, fc='r')
looping = plt.Circle((0,0),R,color='b',fill=False)
ax.add_artist(looping)
time_text = ax.text(-10,R*1.2,'',fontsize=15)

def init():
    time_text.set_text('')
    patch.center = (0, 0)
    ax.add_patch(patch)
    return patch,time_text,


def animate(i):
    t=i/1000.0
    time_text.set_text(t)
    x, y = patch.center
    x = R*np.sin(t/T*2*np.pi)
    y = R*np.cos(t/T*2*np.pi)
    patch.center = (x, y)
    return patch,time_text

slow_motion_factor=1

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               frames=10000,
                               interval=1*slow_motion_factor,
                               blit=True)

plt.show()

我应该补充一点,问题取决于我运行程序的机器。例如,在旧的Intel双核(P8700)(这是程序运行的盒子)上,它比新的i3台式机CPU慢得多。但在后一种情况下,它的速度也会慢得多。

1 个答案:

答案 0 :(得分:1)

问题是,您的计算机速度不够快,每1毫秒传送一张新图像。这是预期的。

你应该寻求更加真实的速度。每秒25帧就足够了 并且还可以及时呈现。

我还对你的代码进行了一些调整,主要是样式和更多的语义变量名称。 最大的变化是将这个答案适应你的代码,以摆脱init之后仍然存在的第一帧: Matplotlib animation: first frame remains in canvas when using blit

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

R = 3
T = 10
time = 3 * T
slow_motion_factor = 1
fps = 50
interval = 1 / fps

fig = plt.figure(figsize=(7.2, 7.2))
ax = fig.add_subplot(1, 1, 1, aspect='equal')
ax.set_xlim(-1.5 * R, 1.5 * R)
ax.set_ylim(-1.5 * R, 1.5 * R)

runner = plt.Circle((0, 0), 0.1, fc='r')
circle = plt.Circle((0, 0), R, color='b', fill=False)
ax.add_artist(circle)
time_text = ax.text(1.1 * R, 1.1 * R,'', fontsize=15)

def init():
    time_text.set_text('')
    return time_text,


def animate(i):
    if i == 0:
        ax.add_patch(runner)
    t = i * interval
    time_text.set_text('{:1.2f}'.format(t))
    x = R * np.sin(2 * np.pi * t / T)
    y = R * np.cos(2 * np.pi * t / T)
    runner.center = (x, y)
    return runner, time_text

anim = animation.FuncAnimation(
    fig,
    animate,
    init_func=init,
    frames=time * fps,
    interval=1000 * interval * slow_motion_factor,
    blit=True,
)

plt.show()