P. *_*eri 7 python matplotlib 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)
Run Code Online (Sandbox Code Playgroud)
但我希望情节有一个传奇,如果我这样做
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()
Run Code Online (Sandbox Code Playgroud)
我最终得到一个包含10个项目的图例.如果我把plt.legend()
循环放在内部,那么每次迭代时图例都会增长......任何解决方案?
目前,您每次plt.plot
进入循环时都要创建一个新的Axes对象.
因此,如果plt.gca().cla()
在使用之前清除当前轴()plt.plot
,并将图例放在循环中,则每次都不会增加图例:
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)
Run Code Online (Sandbox Code Playgroud)
编辑:
正如@tcaswell在评论中指出的那样,使用%matplotlib notebook
magic命令可以为您提供可以更新和重绘的实时图形.
归档时间: |
|
查看次数: |
5045 次 |
最近记录: |