Creating matplotlib animation from plt.imshow in triple for loop

1.7k views Asked by At

I'm having a bit of trouble with matplotlib.animation in the code shown:

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

I have removed my animation attempt for clarity. Basically I want to make a windowed animation that stops after the time specified, without any lag from computation (Running this code shows an animation but is not consistent or smooth running). Is there any way of computing through all the iterations, and then displaying an animated window? I would be thankful for any contribution!

1

There are 1 answers

0
ImportanceOfBeingErnest On

Of course it is perfectly possible to separate the calculation from the animation. One option is to create a large array, the first two dimensions of which hold the grid and the last dimension the timestep. One can then first fill the array and later plot it in an animation.

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