Jupyter笔记本中的Matplotlib动画创建了额外的空图

Chi*_*enk 8 python plot animation matplotlib jupyter

我已经开始为DSP演讲创建一系列交互式笔记本.到目前为止,我已设法复制并实施下面粘贴的MWE.但是,除了包含动画的matplotlib图形之外,我总是得到一个空的Matplotlib窗口.任何想法如何抑制这种行为?

python:3.6.3 matplotlib:2.0和2.1 IPython:5.3.0操作系统:Win 7 64位

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

from matplotlib import animation
from IPython.display import HTML

plt.rcParams['figure.figsize'] = (5,3)
plt.rcParams['figure.dpi'] = 100
plt.rcParams['savefig.dpi'] = 100
plt.rcParams["animation.html"] = "jshtml"  # for matplotlib 2.1 and above, uses JavaScript
#plt.rcParams["animation.html"] = "html5" # for matplotlib 2.0 and below, converts to x264 using ffmpeg video codec
t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = animation.FuncAnimation(fig, animate, frames=len(t))
ani
Run Code Online (Sandbox Code Playgroud)

笔记本还可以在以下位置查看:

https://github.com/chipmuenk/dsp_fpga/blob/master/notebooks/01_LTI/MWE_animation.ipynb

在github的静态渲染中,只显示空的绘图窗口,而不是JavaScript动画.

小智 10

您可以plt.close()在最后一行之前添加。

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

from matplotlib import animation
from IPython.display import HTML

plt.rcParams['figure.figsize'] = (5,3)
plt.rcParams['figure.dpi'] = 100
plt.rcParams['savefig.dpi'] = 100
plt.rcParams["animation.html"] = "jshtml"  # for matplotlib 2.1 and above, uses JavaScript
#plt.rcParams["animation.html"] = "html5" # for matplotlib 2.0 and below, converts to x264 using ffmpeg video codec
t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = animation.FuncAnimation(fig, animate, frames=len(t))
plt.close()
ani
Run Code Online (Sandbox Code Playgroud)


Imp*_*est 8

这与动画无关.

线条

%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
Run Code Online (Sandbox Code Playgroud)

将创建一个空数字的输出.

您可以使用禁止在jupyter笔记本中输出单元格%%capture.

小区1:

%%capture
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.animation
plt.rcParams["animation.html"] = "jshtml"
import numpy as np

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
h = ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
Run Code Online (Sandbox Code Playgroud)

小区2:

ani
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 整齐!在浏览%% capture时,我发现了另一个解决方案:fig,ax = plt.subplots()plt.close(); 也为我做了伎俩.通过关闭图表,"fig"和"ax"的句柄显然不会被删除.是否有理由选择其中一种或另一种解决方案? (5认同)