我想展示一个在循环中计算的数字,比如说 5 次迭代。
这是我写的代码
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,1,100)
y = np.linspace(0,1,100)
xx,yy = np.meshgrid(x,y)
for n in range(5):
a = np.sin(xx-2*n)
plt.imshow(a,interpolation='bilinear')
plt.show()
通过这个代码,我得到了 5 个数字。如何让它每次迭代都以一张图运行?我使用了google collab,是否可以像在matlab中一样在新窗口(未停靠)中打开结果(图)?
/
clear_output
(由Colab 使用)来模拟动画:
import time
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output, display
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
xx, yy = np.meshgrid(x, y)
# you could initialize a subplots or whatever here..
for n in range(5):
a = np.sin(xx - 2 * n)
plt.imshow(a, interpolation="bilinear")
# this one is optional (to verbose my output)
plt.gca().set_title(f"Plot n°{n+1}", fontweight="bold")
# added these three lines
display(plt.gcf())
clear_output(wait=True)
time.sleep(0.5)
plt.show();