我在显示的代码中使用 matplotlib.animation 时遇到了一些问题:
# creates grid of 1's/-1's of dimensions specified.
arr1 = np.random.choice([1.,-1.],[xarray,yarray])
# arr will be the 2-d array iterated.
arr = arr1
# time, row and column loops.
for t in range(0,time1):
for i in range(0,x):
for j in range(0,y):
Echange=energy_change(arr,i,j) # change in energy for this flip.
P_flip = np.exp(-Echange / kT) # probability of this flip occurring.
if random.random() < P_flip: # condition to accept flip.
arr[i][j]=-1*arr[i][j]
image = plt.imshow(arr) # plots image of Ising model after (time) iterations.
if t==0:
plt.show()
else:
plt.draw()
为了清楚起见,我已经删除了我的动画尝试。基本上我想制作一个在指定时间后停止的窗口动画,没有任何计算延迟(运行此代码显示动画,但运行不一致或不流畅)。有没有办法计算所有迭代,然后显示动画窗口?我将感谢您的任何贡献!
最佳答案
当然,将计算与动画分开是完全可能的。 一种选择是创建一个大数组,其中前两个维度保存网格,最后一个维度保存时间步长。然后可以先填充数组,然后将其绘制在动画中。
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
N = 10
T = 100
a = np.zeros((N,N,T))
# creates grid of 1's/-1's of dimensions specified.
a[:,:,0] = np.random.choice([1.,-1.],(N,N) )
# time, row and column loops.
for t in range(1,T):
a[:,:,t] = a[:,:,t-1]
for i in range(0,N):
for j in range(0,N):
P_flip = 0.3
if np.random.random() < P_flip: # condition to accept flip.
a[i,j,t]=-1*a[i,j,t]
#### Plotting #####
fig = plt.figure()
im = plt.imshow(a[:,:,0], interpolation="none", cmap="Blues")
title = plt.title("")
def update(t):
im.set_array(a[:,:,t])
title.set_text(str(t))
ani = matplotlib.animation.FuncAnimation(fig, func=update, frames=T,
repeat=False, interval=100)
plt.show()
关于python - 在三重 for 循环中从 plt.imshow 创建 matplotlib 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379704/