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

aqu*_*tle 7 python matplotlib jupyter

我想做这样的事情:

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

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

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.
Run Code Online (Sandbox Code Playgroud)

我也弄乱了这些东西的一些组合,但是没有任何效果。

这个问题类似于IPython:如何在不同的单元格中显示相同的图?但是我并不是特别想更新我的情节,我只想重画它。

Rom*_*tin 5

我找到了解决方案。诀窍是用轴创建图形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');
Run Code Online (Sandbox Code Playgroud)

这产生 图的第一图

现在,我们可以使用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
Run Code Online (Sandbox Code Playgroud)

请注意我是如何fig在最后一行写的,从而使笔记本再次输出图形。 图的第二个情节!

我希望这有帮助!

  • 太好了,我缺少的关键部分是在单元格的末尾保留了“ fig”,让内核隐式调用了IPython.display.display(fig),而不是我尝试了“ show”等。 (2认同)