Python-我无法从图形动画中保存gif(未生成文件“ .gif”)

时间:2019-06-29 15:39:17

标签: python animation gif

我无法从动画生成gif。我在animate_function中添加了该行,但未保存任何文件。

该图更新了50次,我想将50个更新保存到gif中。动画从按下“运行仿真”按钮开始

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

n0 = 100
n1 = 150
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 == (n1-n0)):
        a.event.source.stop()
    plt.cla()
    plt.subplot(gspec[0, 0]).hist(x1[:n0 + curr], normed=True, bins=20, alpha=0.5, color='green')
    plt.subplot(gspec[0, 1]).hist(x2[:n0 + curr], normed=True, bins=20, alpha=0.5, color='red')
    plt.subplot(gspec[1, 0]).hist(x3[:n0 + curr], normed=True, bins=20, alpha=0.5, color='blue')
    plt.subplot(gspec[1, 1]).hist(x4[:n0 + curr], normed=True, bins=20, alpha=0.5, color='yellow')
    plt.subplot(gspec[0, 0]).set_title('x1\nNormal n={}'.format(n0 + curr))
    plt.subplot(gspec[0, 1]).set_title('x2\nGamma n={}'.format(n0 + curr))
    plt.subplot(gspec[1, 0]).set_title('x3\nExponential n={}'.format(n0 + curr))
    plt.subplot(gspec[1, 1]).set_title('x4\nUniform n={}'.format(n0 + curr))
    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


def update_slider(val):
    x = slider_time.val
slider_time.on_changed(update_slider)

a = [0]
def animate_button(event):
    a[0] = animation.FuncAnimation(fig, update, interval=x, save_count=50)
    a[0].save('test - {} - {}.gif'.format(x, time.strftime("%A %d %B %Y %H:%M:%S")))

#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)

没有错误消息,仅没有为gif生成文件。

0 个答案:

没有答案