Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

python - Matplotlib animation in Jupyter notebook creates additional empty plot

I've started to create a series of interactive notebooks for a DSP lecture. So far, I've managed to copy & implement the MWE pasted below. However, in addition to the matplotlib figure containing the animation, I'm always getting an empty Matplotlib window. Any ideas how to suppress this behaviour?

python: 3.6.3 matplotlib: 2.0 and 2.1 IPython: 5.3.0 OS: Win 7 64 bit

%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

The notebook can also be viewed under:

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

In the static rendering at github, only the empty plot window shows, not the JavaScript animation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This has nothing to do with an animation.

The lines

%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()

will create an output with an empty figure.

You may prevent the output of a cell in jupyter notebook using %%capture.

Cell1:

%%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))

Cell2:

ani

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...