Jupyter:在不同的单元格中重绘

Jupyter: Replot in different cell

我想做这样的事情:

import matplotlib.pyplot as plt
%matplotlib inline
fig1 = plt.figure(1)
plt.plot([1,2,3],[5,2,4])
plt.show()

在一个单元格中,然后在另一个单元格中重新绘制完全相同的图,如下所示:

plt.figure(1) # attempting to reference the figure I created earlier...
# four things I've tried:
plt.show() # does nothing... :(
fig1.show() # throws warning about backend and does nothing
fig1.draw() # throws error about renderer
fig1.plot([1,2,3],[5,2,4]) # This also doesn't work (jupyter outputs some 
# text saying matplotlib.figure.Figure at 0x..., changing the backend and 
# using plot don't help with that either), but regardless in reality
# these plots have a lot going on and I'd like to recreate them 
# without running all of the same commands over again.

我也对这些东西进行了一些组合,但没有任何效果。

这个问题和类似,但我不是特别想更新我的情节,我只是想重画一下。

我找到了解决方法。诀窍是创建一个带有轴 fig, ax = plt.subplots() 的图形并使用该轴进行绘图。然后我们可以在我们想要重新绘制图形的任何其他单元格的末尾调用 fig

import matplotlib.pyplot as plt
import numpy as np

x_1 = np.linspace(-.5,3.3,50)
y_1 = x_1**2 - 2*x_1 + 1

fig, ax  = plt.subplots()
plt.title('Reusing this figure', fontsize=20)
ax.plot(x_1, y_1)
ax.set_xlabel('x',fontsize=18)
ax.set_ylabel('y',fontsize=18, rotation=0, labelpad=10)
ax.legend(['Eq 1'])
ax.axis('equal');

这产生

现在我们可以使用 ax 对象添加更多内容:

t = np.linspace(0,2*np.pi,100)
h, a = 2, 2
k, b = 2, 3
x_2 = h + a*np.cos(t)
y_2 = k + b*np.sin(t)
ax.plot(x_2,y_2)
ax.legend(['Eq 1', 'Eq 2'])
fig

注意我刚刚在最后一行写了fig,让笔记本再次输出这个数字。

希望对您有所帮助!