我有一个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);
每个单元格的开头标记为#%%。第三个单元显示一个空的数字。
我知道plt.subplots(2)
可以从一个单元格绘制2个图表,但这不会让我在图表之间有标记。
提前感谢您的帮助。
答案 0 :(得分:4)
此answer to a similar question表示您可以重复使用之前单元格中的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.
答案 1 :(得分:2)
我能想到的最简单的事情是将绘图提取到一个可以调用两次的函数中。在第二个电话上,您也可以拨打plt.xlim
进行放大。所以就像(使用%%
表示新单元格一样):
# %%
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# %%
def make_plot():
x = np.linspace(0, 2 * np.pi)
y = np.sin(x ** 2)
plt.plot(x, y);
make_plot()
# %%
Some markdown text to explain what's going on before we zoom in on the interesting bit
# %%
make_plot()
plt.xlim(xmax=2)