在iPython Notebook中动态更新图 [英] 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). 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
magic命令可以为您提供一个可以更新和重绘的实时图形.
As @tcaswell pointed out in comments, using the %matplotlib notebook
magic command gives you a live figure which can update and redraw.
这篇关于在iPython Notebook中动态更新图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!