[英]Dynamically update plot in iPython notebook
As referred in this question , I am trying to update a plot dynamically in an iPython notebook (in one cell). 正如在这个问题中提到的,我试图在iPython笔记本中(在一个单元格中)动态更新绘图。 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. 不同之处在于我不想绘制新行,但是我的x_data和y_data在某个循环的每次迭代中都在增长。
What I'd like to do is: 我想做的是:
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()
I end up with a legend which contains 10 items. 我最终得到一个包含10个项目的图例。 If I put the plt.legend()
inside the loop, the legend grows at each iteration... Any solution? 如果我把plt.legend()
放在循环中,图例会在每次迭代时增长...任何解决方案?
Currently, you are creating a new Axes object for every time you plt.plot
in the loop. 目前,您每次在循环中plt.plot
时都会创建一个新的Axes对象。
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: 因此,如果在使用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)
EDIT: As @tcaswell pointed out in comments, using the %matplotlib notebook
magic command gives you a live figure which can update and redraw. 编辑:正如@tcaswell在评论中指出的那样,使用%matplotlib notebook
magic命令为您提供了可以更新和重绘的实时图形。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.