Python Matplotlib with Jupyter 上随时间变化的图

Plots that varies over the time on Python Matplotlib with Jupyter

在接下来的几行中,我报告了一个代码,该代码生成一个随时间变化的图 Python 在 Anaconda Spyder

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-3, 3, 0.01)
N = 1
fig = plt.figure()
ax = fig.add_subplot(111)
for N in range(8):
    y = np.sin(np.pi*x*N)
    line, = ax.plot(x, y)
    plt.draw()
    plt.pause(0.5)
    line.remove()

我想用 Jupyter 做一些,但这是不可能的。特别是 Matplotlib 方法 .pause() 在 Jupyter 上似乎不存在。 有没有人可以向我解释这种差异,并可以帮助我在 Jupyter 上使用 Python 构建随时间变化的绘图代码?

如果我 select 一个 interactive backend 使用魔术命令 %matplotlib,它对我有用;您的 Jupyter 笔记本设置可能设置为内联显示图。

import matplotlib.pyplot as plt
import numpy as np

%matplotlib

x = np.arange(-3, 3, 0.01)
N = 1
fig = plt.figure()
ax = fig.add_subplot(111)
for N in range(8):
    y = np.sin(np.pi*x*N)
    line, = ax.plot(x, y)
    plt.draw()
    plt.pause(0.5)
    line.remove()

要恢复您的设置,请使用魔法 %matplotlib inline