加速matplotlib中的动画

2024-05-19 18:19:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在想办法加快这个动画的速度。我要整件事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


Tags: textimportalphatruematplotlibasnpplt
1条回答
网友
1楼 · 发布于 2024-05-19 18:19:23

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

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

...

逻辑基本上是通过从值数组中取较大的一部分来加快FuncAnimate绘制每个图形的速度。在

相关问题 更多 >