从triple for循环中的plt.imshow创建matplotlib动画

时间:2016-12-29 12:25:34

标签: python animation matplotlib jquery-animate imshow

我在显示的代码中遇到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()

为了清晰起见,我已删除了我的动画尝试。基本上我想制作一个窗口动画,在指定的时间后停止,没有任何计算延迟(运行此代码显示动画但不一致或平稳运行)。有没有办法计算所有迭代,然后显示动画窗口?我会感谢任何贡献!

1 个答案:

答案 0 :(得分:1)

当然,完全可以将计算与动画分开。 一种选择是创建一个大型数组,其前两个维度保持网格,最后一个维度为时间步长。然后可以先填充数组,然后将其绘制成动画。

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()