如何在jupyter中显示动图
时间: 2024-05-12 14:20:36 浏览: 12
要在jupyter中显示动态图,需要使用IPython的display模块和matplotlib的animation模块。
首先,需要导入这两个模块:
```python
from IPython.display import display
from matplotlib import animation
```
接下来,创建一个函数,用于生成动态图。这个函数需要返回一个matplotlib的Figure对象:
```python
def animate():
fig = plt.figure()
# ...
return fig
```
然后,可以使用animation.FuncAnimation来创建一个动画对象。这个函数需要传入三个参数:Figure对象、更新图形的函数以及帧数。更新图形的函数需要一个参数,表示当前帧的编号。这个函数需要返回一组更新后的Artists对象(例如,Line2D对象),这些对象将被用于更新图形。
```python
anim = animation.FuncAnimation(animate(), update, frames=100)
```
最后,使用display函数将动画对象显示出来:
```python
display(anim)
```
完整的示例代码如下所示:
```python
from IPython.display import display
from matplotlib import animation
import matplotlib.pyplot as plt
import numpy as np
def animate():
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 200)
line, = ax.plot(x, np.sin(x))
def update(frame):
line.set_ydata(np.sin(x + frame / 10.0))
return line,
ax.set_ylim(-1.1, 1.1)
anim = animation.FuncAnimation(fig, update, frames=100, blit=True)
return anim
anim = animate()
display(anim)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)