如何在下一个jupyter单元格中重用绘图

blo*_*ley 6 python matplotlib ipython jupyter-notebook

我有一个jupyter笔记本,并希望在一个单元格中创建一个绘图,然后写下一些降价来解释它,然后设置限制并在下一个再次绘制.到目前为止这是我的代码:

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

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

plt.plot(x, y);

# %%
Some markdown text to explain what's going on before we zoom in on the interesting bit

# %%
plt.xlim(xmax=2);
Run Code Online (Sandbox Code Playgroud)

每个单元格的开头标记为#%%.第三个单元显示一个空图.

我知道plt.subplots(2)从一个单元格绘制2个图,但这不会让我在图之间有标记.

在此先感谢您的帮助.

NHD*_*aly 10

对类似问题的回答表示您可以重复使用以前的单元格中的axes和。figure似乎如果您只将figure单元格中的最后一个元素作为它的最后一个元素,它将重新显示其图形:

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

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

fig, ax = plt.subplots()
ax.plot(x, y);
fig  # This will show the plot in this cell, if you want.

# %%
Some markdown text to explain what's going on before we zoom in on the interesting bit

# %%
ax.xlim(xmax=2);  # By reusing `ax`, we keep editing the same plot.
fig               # This will show the now-zoomed-in figure in this cell.
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用“pandas”,绘图函数将返回“matplotlib Axes”对象。您可以执行诸如“ax = df.plot()”之类的操作,然后在后面的单元格中执行“ax.get_figure()”,这将重新绘制图形 (3认同)