如何在 IPython 笔记本中的循环中动态更新绘图(在一个单元格内) [英] How to dynamically update a plot in a loop in IPython notebook (within one cell)

查看:13
本文介绍了如何在 IPython 笔记本中的循环中动态更新绘图(在一个单元格内)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:Python 2.7、Matplotlib 1.3、IPython notebook 1.1、Linux 和 Chrome.代码位于一个输入单元格中,使用 --pylab=inline.

Environment: Python 2.7, Matplotlib 1.3, IPython notebook 1.1, Linux, and Chrome. The code is in one single input cell, using --pylab=inline.

我想使用 IPython notebook 和 Pandas 来消费一个流并每五秒动态更新一个情节.

I want to use IPython notebook and Pandas to consume a stream and dynamically update a plot every five seconds.

当我只使用打印语句以文本格式打印数据时,它工作得非常好:输出单元格只是继续打印数据并添加新行.但是当我尝试绘制数据(然后在循环中更新它)时,该图永远不会出现在输出单元格中.但如果我删除循环,只绘制一次,它就可以正常工作.

When I just use a print statement to print the data in text format, it works perfectly fine: the output cell just keeps printing data and adding new rows. But when I try to plot the data (and then update it in a loop), the plot never shows up in the output cell. But if I remove the loop, and just plot it once, it works fine.

然后我做了一些简单的测试:

Then I did some simple test:

i = pd.date_range('2013-1-1',periods=100,freq='s')
while True:
    plot(pd.Series(data=np.random.randn(100), index=i))
    #pd.Series(data=np.random.randn(100), index=i).plot() also tried this one
    time.sleep(5)

在我手动中断进程之前,输出不会显示任何内容(Ctrl + M + I).在我打断它之后,该图正确显示为多条重叠线.但我真正想要的是一个每五秒显示并更新一次的图(或者每当 plot() 函数被调用时,就像我上面提到的打印语句输出一样,效果很好).仅在单元格完成后才显示最终图表 不是我想要的.

The output will not show anything until I manually interrupt the process (Ctrl + M + I). And after I interrupt it, the plot shows correctly as multiple overlapped lines. But what I really want is a plot that shows up and gets updated every five seconds (or whenever the plot() function gets called, just like what print statement outputs I mentioned above, which works well). Only showing the final chart after the cell is completely done is not what I want.

我什至尝试在每个 plot() 等之后显式添加 draw() 函数.它们都不起作用.如何通过 for/while 循环在 IPython 笔记本中的一个单元格内动态更新绘图?

I even tried to explicitly add the draw() function after each plot(), etc. None of them works. How can I dynamically update a plot by a for/while loop within one cell in IPython notebook?

推荐答案

使用 IPython.display 模块:

%matplotlib inline
import time
import pylab as pl
from IPython import display
for i in range(10):
    pl.plot(pl.randn(100))
    display.clear_output(wait=True)
    display.display(pl.gcf())
    time.sleep(1.0)

这篇关于如何在 IPython 笔记本中的循环中动态更新绘图(在一个单元格内)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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