我想做这样的事情:
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.
我已经搞砸了这些东西的一些组合,但没有任何作用。
这个问题类似于IPython: How to show the same plot in different cells?,但我并不是特别希望更新我的情节,我只是想重新绘制它。
答案 0 :(得分:3)
我找到了解决方案。诀窍是创建带有轴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
的,从而使笔记本再次输出图形。
我希望这会有所帮助!