Jupyter:在不同单元格中的重复 [英] Jupyter: Replot in different cell

查看:368
本文介绍了Jupyter:在不同单元格中的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

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

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

In one cell, and then redraw the exact same plot in another cell, like so:

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.

我也弄乱了这些东西的一些组合,但是没有用.

I've messed around with some combinations of this stuff as well but nothing works.

此问题类似于 IPython:如何在不同的单元格中显示相同的图?,但是我并不是特别想更新我的图,我只想重绘它.

This question is similar to IPython: How to show the same plot in different cells? but I'm not particularly looking to update my plot, I just want to redraw it.

推荐答案

我找到了解决此问题的方法.诀窍是创建具有轴fig, ax = plt.subplots()的图形并使用该轴进行绘制.然后,我们可以在要重新绘制图形的任何其他单元格的末尾调用fig.

I have found a solution to do this. The trick is to create a figure with an axis fig, ax = plt.subplots() and use the axis to plot. Then we can just call fig at the end of any other cell we want to replot the figure.

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对象添加更多内容:

Now we can add more things by using the 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

请注意,我是如何在最后一行中编写fig的,从而使笔记本再次输出了该图.

Note how I just wrote fig in the last line, making the notebook output the figure once again.

我希望这会有所帮助!

这篇关于Jupyter:在不同单元格中的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆