动态更新 iPython 笔记本中的绘图

Dynamically update plot in iPython notebook

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

我想做的是:

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) 

但我希望剧情有传奇色彩,如果有的话

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() 放在循环中,图例会在每次迭代时增长......有什么解决方案吗?

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

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

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 魔法命令可以为您提供可以更新和重绘的实时图形。