"使用iPython笔记本动态更新图表"

2024-10-17 08:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

this question所述,我试图在iPython笔记本(一个单元格)中动态更新绘图。 不同的是,我不想绘制新行,但我的x_数据和y_数据在某个循环的每次迭代中都在增长。

我想做的是:

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


Tags: the数据importnumpytimeasdisplaynp