动画不是从按钮单击事件启动的

时间:2019-06-29 10:57:06

标签: python matplotlib animation button slider

我对代码做了几处更改,有一次我的动画停止显示。我不知道代码的哪一部分阻止了动画的运行(我认为是在创建update_slider函数时)。这个想法是通过单击按钮小部件来启动动画。

这个想法是允许用户使用滑块值调整动画的速度。此值传递给FuncAnimation的interval参数

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.animation as animation
from matplotlib.widgets import Slider, Button
import time

%matplotlib notebook

n = 10000
x1 = np.random.normal(-2.5, 1, n)
x2 = np.random.gamma(2, 1.5, n)
x3 = np.random.exponential(2, n)+7
x4 = np.random.uniform(14, 20, n)

def update(curr):
    if curr * 100 > n:
        a.event_source.stop()
    plt.cla()
    plt.subplot(gspec[0, 0]).hist(x1[:curr * 100], normed=True, bins=20, alpha=0.5, color='green')
    plt.subplot(gspec[0, 1]).hist(x2[:curr * 100], normed=True, bins=20, alpha=0.5, color='red')
    plt.subplot(gspec[1, 0]).hist(x3[:curr * 100], normed=True, bins=20, alpha=0.5, color='blue')
    plt.subplot(gspec[1, 1]).hist(x4[:curr* 100], normed=True, bins=20, alpha=0.5, color='yellow')
    plt.subplot(gspec[0, 0]).set_title('x1\nNormal n={}'.format(curr * 100))
    plt.subplot(gspec[0, 1]).set_title('x2\nGamma n={}'.format(curr * 100))
    plt.subplot(gspec[1, 0]).set_title('x3\nExponential n={}'.format(curr * 100))
    plt.subplot(gspec[1, 1]).set_title('x4\nUniform n={}'.format(curr * 100))
    fig.canvas.draw_idle()

fig = plt.figure()
gspec = gridspec.GridSpec(3, 2, height_ratios=[10,10,1])
gspec.update(wspace=1, hspace=1)
for ax in [plt.subplot(gspec[0, 0])]:
    ax.set_xlim(-7, 2)
for ax in [plt.subplot(gspec[0, 1])]:
    ax.set_xlim(-1, 13)
for ax in [plt.subplot(gspec[1, 0])]:
    ax.set_xlim(7, 17)
for ax in [plt.subplot(gspec[1, 1])]:
    ax.set_xlim(14, 20)
for ax in [plt.subplot(gspec[0, 0]), plt.subplot(gspec[0, 1]), plt.subplot(gspec[1, 0]), plt.subplot(gspec[1, 1])]:
    ax.set_ylim(0, 0.7)

slider_axcolor = 'lightgoldenrodyellow'
ax_time = plt.subplot(gspec[2:, 0:])
rect = ax_time.patch
rect.set_facecolor(slider_axcolor)
slider_time = Slider(ax_time, 'timer\n(ms)', 1, 100, valinit=1, valstep=1)
x = slider_time.valinit

slider_time.on_changed(update_slider)

def animate_button(x):
    a = animation.FuncAnimation(fig, update, interval=x)

def update_slider(val):
    x = slider_time.val

#animation button
ax_launch = plt.axes([0.785, 0.02,0.2, 0.075])
ax_launch.xaxis.set_visible(False)
ax_launch.yaxis.set_visible(False)
button_launch = Button(ax_launch, label='Run Simulations')
button_launch.on_clicked(animate_button(x))

plt.show()

我没有收到任何错误消息,只是动画没有开始。 非常感谢你的帮助。更进一步,我想保存动画的gif(我在丢失的代码的早期版本中对其进行了管理!)

0 个答案:

没有答案