在 iPython 笔记本中动态更新绘图 [英] Dynamically update plot in iPython notebook

查看:31
本文介绍了在 iPython 笔记本中动态更新绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题,我正在尝试在 iPython 笔记本中(在一个单元格中)动态更新绘图.不同之处在于我不想绘制新线,但我的 x_data 和 y_data 在某个循环的每次迭代中都在增长.

As referred in this question, I am trying to update a plot dynamically in an iPython notebook (in one cell). The difference is that I don't want to plot new lines, but that my x_data and y_data are growing at each iteration of some loop.

我想做的是:

import numpy as np
import time
plt.axis([0, 10, 0, 100]) # supoose I know what the limits are going to be
plt.ion()
plt.show()
x = []
y = []
for i in range(10):
     x = np.append(x, i)
     y = np.append(y, i**2)
     # update the plot so that it shows y as a function of x
     time.sleep(0.5) 

但我希望情节有一个传说,如果我这样做了

but I want the plot to have a legend, and if I do

from IPython import display
import time
import numpy as np
plt.axis([0, 10, 0, 100]) # supoose I know what the limits are going to be
plt.ion()
plt.show()
x = []
y = []
for i in range(10):
    x = np.append(x, i)
    y = np.append(y, i**2)
    plt.plot(x, y, label="test")
    display.clear_output(wait=True)
    display.display(plt.gcf())
    time.sleep(0.3)
plt.legend()

我最终得到了一个包含 10 个项目的图例.如果我将 plt.legend() 放在循环中,图例在每次迭代中都会增长......有什么解决方案吗?

I end up with a legend which contains 10 items. If I put the plt.legend() inside the loop, the legend grows at each iteration... Any solution?

推荐答案

目前,您每次 plt.plot 在循环中都会创建一个新的 Axes 对象.

Currently, you are creating a new Axes object for every time you plt.plot in the loop.

因此,如果您在使用 plt.plot 之前清除当前轴(plt.gca().cla()),并将图例放入循环中,它不会每次都增加图例:

So, if you clear the current axis (plt.gca().cla()) before you use plt.plot, and put the legend inside the loop, it works without the legend growing each time:

import numpy as np
import time
from IPython import display

x = []
y = []
for i in range(10):
    x = np.append(x, i)
    y = np.append(y, i**2)
    plt.gca().cla() 
    plt.plot(x,y,label='test')
    plt.legend()
    display.clear_output(wait=True)
    display.display(plt.gcf()) 
    time.sleep(0.5) 

正如@tcaswell 在评论中指出的那样,使用 %matplotlib notebook 魔术命令可以为您提供一个可以更新和重绘的实时图形.

As @tcaswell pointed out in comments, using the %matplotlib notebook magic command gives you a live figure which can update and redraw.

这篇关于在 iPython 笔记本中动态更新绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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