简体   繁体   English

在随后的IPython笔记本单元格中重新显示修改后的绘图

[英]Redisplaying modified plot in subsequent IPython notebook cells

I am creating a demo using IPython notebook. 我正在使用IPython笔记本创建一个演示。 I launch the notebook in the pylab inline mode, eg ipython notebook --pylab=inline , and what I would like to do is progressively build a plot, modifying aspects of the plot in subsequent cells, and having the chart redisplay after each modification. 我以pylab内联模式启动笔记本,例如ipython notebook --pylab=inline ,我想要做的是逐步构建一个绘图,修改后续单元格中的绘图方面,并在每次修改后重新显示图表。 For instance, I would like to have consecutive cells, 例如,我想要连续的细胞,

CELL 1: CELL 1:

from pandas.io.data import DataReader
from datetime import datetime
import matplotlib.pyplot as plt

goog = DataReader("GOOG",  "yahoo", datetime(2000,1,1), datetime(2012,1,1))
close_vals = goog['Close']
plot(close_vals.index, close_vals.values)

CHART DISPLAYED INLINE

CELL 2: 细胞2:

xlim(datetime(2009,1,1), datetime(2010,1,1))

MODIFIED CHART DISPLAYED INLINE

However, the original chart doesn't seem to make it's way into subsequent cells, and the chart displayed in CELL 2 is empty. 但是,原始图表似乎没有进入后续单元格,并且CELL 2中显示的图表为空。 In order to see the original plot with the modification, I have to re-issue the plot command, 为了通过修改看原始图,我必须重新发出plot命令,

CELL 2: 细胞2:

plot(close_vals.index, close_vals.values)
xlim(datetime(2009,1,1), datetime(2010,1,1))

This quickly gets clunky and inelegant as I add moving average trend lines and labels. 当我添加移动平均线趋势线和标签时,这很快变得笨重而且不优雅。 Also, working from the IPython console, this method of progressively building a plot works just fine. 此外,在IPython控制台上工作,这种逐步构建绘图的方法也可以正常工作。 Anyone know of a better way to create this kind of demo in the notebook? 有谁知道在笔记本中创建这种演示的更好方法? Thanks. 谢谢。

UPDATE: 更新:

My final code ended up looking like this. 我的最终代码最终看起来像这样。

CELL 1: CELL 1:

from pandas.io.data import DataReader
from datetime import datetime
import matplotlib.pyplot as plt

goog = DataReader("GOOG",  "yahoo", datetime(2000,1,1), datetime(2012,1,1))
close_vals = goog['Close']
fig, ax = subplots(1,1)
ax.plot(close_vals.index, close_vals.values,label='GOOG Stock Price')

CELL 2: 细胞2:

ax.set_xlim(datetime(2009,1,1), datetime(2010,1,1))
fig

CELL 3: 细胞3:

avg_20 = [ sum(close_vals.values[i-20:i])/20.0 for i in range(20,len(close_vals))]
avg_20_times = close_vals.index[20:]
ax.plot(avg_20_times, avg_20, label='20 day trailing average')
ax.legend()
fig

After updating ax in each subsequent cell, calling fig redisplays the plot; 在每个后续单元格中更新ax后,调用fig重新显示该图; exactly what I was looking for. 正是我在寻找的东西。 Thanks! 谢谢!

You can use variables to reference the figure and Axe objects: 您可以使用变量来引用图形和Axe对象:

In cell 1: 在单元格1中:

fig, ax = subplots(1, 1)
plot(randn(100));

In cell 2: 在单元格2中:

ax.set_xlim(20, 40)
fig

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM