我找到了一个解决方案来做到这一点。诀窍是创建一个带有轴的图形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');
This produces
现在我们可以使用添加更多东西ax
object:
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
Note how I just wrote fig
in the last line, making the notebook output the figure once again.
我希望这有帮助!