![](/img/trans.png)
[英]How to dynamically update a plot in a loop in Ipython notebook (within one cell)
[英]Dynamically update plot in iPython notebook
正如在這個問題中提到的,我試圖在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
magic命令為您提供了可以更新和重繪的實時圖形。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.