在matplotlib中加速动画

时间:2018-05-09 10:49:05

标签: python animation matplotlib

我正在试图弄清楚如何加快这个动画。我希望整件事能在30秒内完成。

我已经尝试在FuncAnimation中调整帧之间的间隔,保存计数,但它似乎不起作用。无论如何只是设置总持续时间并让matplotlib将所有内容都压缩到该时间限制内?

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation #1
n = 500
x = np.random.randn(n)

%matplotlib notebook

# generate 4 random variables from the random, gamma, exponential, and uniform distributions
x1 = np.random.normal(-2.5, 1, 10000)
x2 = np.random.gamma(2, 1.5, 10000)
x3 = np.random.exponential(2, 10000)+7
x4 = np.random.uniform(14,20, 10000)

def update(curr):
    # check if animation is at the last frame, and if so, stop the animation a
    if curr == n: 
        a.event_source.stop()

    plt.cla()
    plt.hist(x1[:curr], normed=True, bins=20, alpha=0.5)
    plt.hist(x2[:curr], normed=True, bins=20, alpha=0.5)
    plt.hist(x3[:curr], normed=True, bins=20, alpha=0.5)
    plt.hist(x4[:curr], normed=True, bins=20, alpha=0.5)
    plt.axis([-7,21,0,0.6])
    plt.text(x1.mean()-1.5, 0.5, 'Normal')
    plt.text(x2.mean()-1.5, 0.5, 'Gamma')
    plt.text(x3.mean()-1.5, 0.5, 'Exponential')
    plt.text(x4.mean()-1.5, 0.5, 'Uniform')

    plt.annotate('n = {}'.format(curr), [3,27])

fig = plt.figure()
fig = plt.figure(figsize=(9,3))
a = animation.FuncAnimation(fig, update, interval=10, blit=True, save_count=500)

最终产品如下所示:

enter image description here

1 个答案:

答案 0 :(得分:0)

我得到了一个建议的答案:

...
def update(curr)
  x = 100 #x as speed multiplier
  curr = curr*x 
  if curr >= n:
    a.event_source.stop()

...

逻辑基本上是通过采用值数组的较大子部分来加快FuncAnimate绘制每个图形的速率。