如何在Jupyter中显示动画?

huangapple go评论71阅读模式
英文:

How do I show animation in Jupyter?

问题

我从手册中复制了代码并在新的笔记本中运行它。

不幸的是,我只看到了图形:

如何在Jupyter中显示动画?

(并且单元格上标有“*”)。

当我重新启动内核时,有时我会看到动画的开头:

如何在Jupyter中显示动画?

但我从未看到matplotlib手册中提到的控件。

服务器信息:
您正在使用Jupyter Notebook。

笔记本服务器的版本是:6.5.4-762f3618
服务器正在运行的Python版本是:
Python 3.10.6(主要版本,2023年5月29日,11:10:38)[GCC 11.3.0]

当前内核信息:
Python 3.10.6(主要版本,2023年5月29日,11:10:38)[GCC 11.3.0]

我可以将动画保存为mp4文件并查看它,但我更喜欢交互式功能。

我做错了什么?

英文:

I copied code from the manual:

%matplotlib notebook

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig, ax = plt.subplots()
t = np.linspace(0, 3, 40)
g = -9.81
v0 = 12
z = g * t**2 / 2 + v0 * t

v02 = 5
z2 = g * t**2 / 2 + v02 * t

scat = ax.scatter(t[0], z[0], c="b", s=5, label=f'v0 = {v0} m/s')
line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0]
ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time 
展开收缩
', ylabel='Z [m]') ax.legend() def update(frame): # for each frame, update the data stored on each artist. x = t[:frame] y = z[:frame] # update the scatter plot: data = np.stack([x, y]).T scat.set_offsets(data) # update the line plot: line2.set_xdata(t[:frame]) line2.set_ydata(z2[:frame]) return (scat, line2) ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30) plt.show()

into a new notebook and run it.

Alas, all I see is the figure:

如何在Jupyter中显示动画?

(and the cell is marked with *).

When I restart the kernel, sometimes I get the beginning of the animation:

如何在Jupyter中显示动画?

but I never get the controls present in the matplotlib manual.

Server Information:
You are using Jupyter Notebook.

The version of the notebook server is: 6.5.4-762f3618
The server is running on this version of Python:
Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]

Current Kernel Information:
Python 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]

I can save the animation in an mp4 file and view it, but I would much prefer the interactive facility.

What am I doing wrong?

答案1

得分: 1

在导入库之后,请添加以下内容:

from matplotlib import rc
rc('animation', html='jshtml')

然后在此处调用 ani

ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
plt.show()
ani

这将打开交互式窗口。

英文:

Include the following after importing the libraries:

from matplotlib import rc
rc('animation', html='jshtml')

Then call ani here:

ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
plt.show()
ani

This would bring the interactive window.

huangapple
  • 本文由 发表于 2023年7月7日 03:39:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定