gpt4 book ai didi

python - 在 iPython notebook 中动态更新绘图

转载 作者:太空狗 更新时间:2023-10-29 21:45:58 26 4
gpt4 key购买 nike

this question 中所述,我正在尝试在 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 魔术命令可以为您提供可以更新和重绘的实时图形。

关于python - 在 iPython notebook 中动态更新绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com