如何在下一个jupyter单元中重用绘图 [英] How to reuse plot in next jupyter cell

查看:142
本文介绍了如何在下一个jupyter单元中重用绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a jupyter notebook and wish to create a plot in one cell, then write some markdown to explain it in the next, then set the limits and plot again in the next. This is my code so far:

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

每个单元格的开始都在上面#%%处标记.第三个单元格显示一个空数字.

The start of each cell is marked # %% above. The third cell shows an empty figure.

我知道plt.subplots(2)可以从一个像元绘制2个图,但这并不能让我在图之间进行降价.

I'm aware of plt.subplots(2) to plot 2 plots from one cell but this does not let me have markdown between the plots.

在此先感谢您的帮助.

推荐答案

对此类似问题的答案说,您可以重用上一个单元格中的axesfigure.似乎,如果仅将figure作为单元格中的最后一个元素,它将重新显示其图形:

This answer to a similar question says you can reuse your axes and figure from a previous cell. It seems that if you just have figure as the last element in the cell it will re-display its graph:

# %%
%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.

这篇关于如何在下一个jupyter单元中重用绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆