2ya*_*yan 5 python animation matplotlib jupyter-notebook
我遇到的问题是,在 jupyter 笔记本中显示 JavaScript 动画也会显示该图:
示例代码:
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
HTML(anim.to_jshtml())
Run Code Online (Sandbox Code Playgroud)
请注意,这会产生两个绘图,而不仅仅是动画。
另一方面,我尝试使用以下命令运行它:
HTML(anim.to_html5_video())
Run Code Online (Sandbox Code Playgroud)
但这给了我以下错误之一:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Continuum\miniconda3\lib\site-packages\matplotlib\animation.py in __getitem__(self, name)
169 try:
--> 170 return self.avail[name]
171 except KeyError:
KeyError: 'ffmpeg'
During handling of the above exception, another exception occurred:
RuntimeError Traceback (most recent call last)
<ipython-input-30-b5253c68f7fe> in <module>()
20 frames=200, interval=20, blit=True)
21
---> 22 HTML(anim.to_html5_video())
~\AppData\Local\Continuum\miniconda3\lib\site-packages\matplotlib\animation.py in to_html5_video(self, embed_limit)
1347 # We create a writer manually so that we can get the
1348 # appropriate size for the tag
-> 1349 Writer = writers[rcParams['animation.writer']]
1350 writer = Writer(codec='h264',
1351 bitrate=rcParams['animation.bitrate'],
~\AppData\Local\Continuum\miniconda3\lib\site-packages\matplotlib\animation.py in __getitem__(self, name)
171 except KeyError:
172 raise RuntimeError(
--> 173 'Requested MovieWriter ({}) not available'.format(name))
174
175
RuntimeError: Requested MovieWriter (ffmpeg) not available
Run Code Online (Sandbox Code Playgroud)
并且安装 ffmpeg 没有帮助。
我相信,因为笔记本是交互式的,所以您无需调用即可自动获取绘图plt.show。您可以调用plt.close手动关闭它(或更改交互模式,但您可能希望保留它用于其他用途)。
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
plt.close(fig)
...
Run Code Online (Sandbox Code Playgroud)
我只需确保 ffmpeg 安装正确即可开始HTML(anim.to_html5_video())工作。看来Python就是找不到它。
| 归档时间: |
|
| 查看次数: |
2258 次 |
| 最近记录: |