gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:05:42 24 4
gpt4 key购买 nike

我想做这样的事情:

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

最佳答案

我已经找到了解决方法。诀窍是创建一个带有轴的图形 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');

这产生 First plot of the figure

现在我们可以使用 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 的,使笔记本再次输出图形。 Second plot of the figure!

希望对您有所帮助!

关于python - Jupyter:在不同的单元格中重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com