【问题标题】:Jupyter: Replot in different cellJupyter:在不同的单元格中重新绘制
【发布时间】:2016-09-05 21:46:47
【问题描述】:

我想做这样的事情:

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?,但我并不是特别想更新我的情节,我只是想重绘它。

【问题讨论】:

  • 不要认为你可以用 inline 做到这一点,它会丢弃 python 端的对象并将一个 png 和 base64 编码的文本存储在笔记本中。你应该可以用 nbagg (%matplotlib notebook) 做到这一点,你绝对可以用 ipympl 做到这一点

标签: python matplotlib jupyter


【解决方案1】:

我找到了解决方案。诀窍是创建一个带有轴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,使笔记本再次输出数字。

我希望这会有所帮助!

【讨论】:

  • 非常好,我缺少的关键部分是在单元格末尾留下fig,让内核隐式调用 IPython.display.display(fig),而不是我尝试使用show
  • 嘿,这可以显示情节,但是如果我想保存呢?
  • > matplotlib.pyplot.savefig(...) > 保存当前图形。见here。我希望这能“正常工作”。
猜你喜欢
  • 2018-10-31
  • 1970-01-01
  • 2018-04-19
  • 2017-12-14
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多