Python - я не могу сохранить gif из графической анимации (файл '.gif' не сгенерирован) - PullRequest
0 голосов
/ 29 июня 2019

Я не могу сгенерировать 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.

...