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

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

问题描述

环境:Python 2.7,matplotlib 1.3,IPython笔记本1.1,linux,chrome。代码在一个单独的输入单元格中,使用 - pylab = inline

Environment: Python 2.7, matplotlib 1.3, IPython notebook 1.1, linux, chrome. The code is in one single input cell, using --pylab=inline

我想使用IPython笔记本和pandas使用流并每5秒动态更新一个绘图。

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

当我只使用print语句以文本格式打印数据时,它完全正常工作:输出单元格只保留打印数据并添加新行。但是当我尝试绘制数据(然后在循环中更新它)时,绘图永远不会出现在输出单元格中。但如果我删除循环,只需绘制一次。它工作正常。

When I just use 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 show up in the output cell. But if I remove the loop, 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)之前,输出不会显示任何内容。在我中断它之后,该图正确地显示为多个重叠的行。但我真正想要的是一个显示并每5秒更新一次的情节(或者每当调用 plot()函数时,就像我上面提到的print语句输出一样,效果很好)。仅在完成单元格后才显示最终图表不是我想要的。

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 5 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.

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

I even tried to explicitly add draw() function after each plot(), etc. None of them works. Wonder how to 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天全站免登陆