0
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation 
plt.style.use('seaborn-pastel')


### random no. generated uniformly from 1 to 6
x = np.random.uniform(low = 1 , high = 6 ,size = 10)
x.mean()




### making a list of items for the plot
avg = []
trials = []
for j in range(1,100000):
    x = np.random.uniform(low = 1 , high = 6 ,size = j).mean()
    avg.append(x)
    y = j
    trials.append(y)





import matplotlib as mpl
mpl.rcParams['agg.path.chunksize'] = 10000

ax = plt.axes(xlim=(0,100000), ylim=(2, 4))
line, = ax.plot([], [], lw=3)
fig = plt.figure()

def init():
    line.set_data([], [])
    return line,
xdata , ydata = [], []
def animate(i):
    x = trials
    y = avg
    xdata.append(x)  
    ydata.append(y)  
    line.set_data(xdata, ydata)
    return line,

anim = FuncAnimation(fig, animate, init_func=init , frames = 500 ,interval = 20 , blit = True)

anim.save('simulation1.mp4', dpi=150, fps = 30, writer='ffmpeg',extra_args=['-vcodec', 'libx264'])
plt.show()

我无法理解为什么动画在 jupyter notebook 和 spyder 中都没有发生。此外,当我尝试将文件另存为 mp4 时,它会另存为空白视频。任何帮助,将不胜感激。

4

1 回答 1

0

我的环境是一个“jupyter 实验室”,所以我将它描述为在两者上运行。请参考评论并在评论之间切换。

修复:

  • %matplotlib nbagg
  • line.set_data(trains[:1],avg[:1])
  • 删除打印样式表
    # jupyter notebook inline display
    %matplotlib nbagg

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation 
    import matplotlib as mpl

    # Jupyter lab
    # from IPython.display import HTML
    # %matplotlib inline

    # making a list of items for the plot
    avg = []
    trials = []
    for j in range(1,101):
        y = np.random.uniform(low = 1 , high = 6 ,size = j).mean()
        avg.append(y)
        x = j
        trials.append(x)

    fig = plt.figure()
    ax = plt.axes(xlim=(0,100), ylim=(2, 4))
    line, = ax.plot([], [], 'r-', lw=3)

    def animate(i):
        line.set_data(trials[:i], avg[:i])
        return line,

    anim = FuncAnimation(fig, animate, interval=20)

    anim.save('simulation1.mp4', dpi=150, fps=30, writer='ffmpeg', extra_args=['-vcodec', 'libx264'])
    # jyupter notebook
    plt.show()

    # jupyter lab 
    # plt.close()
    # HTML(anim.to_html5_video())

在此处输入图像描述

于 2020-06-11T07:43:21.300 回答