terman
terman

Reputation: 165

Plot of a changing matrix ... gone wrong

I am trying to plot a matrix in Python. So, my initial thought was using matshow.

However, this particular matrix develop over time via an algorithm (the function sandpile below), so I need to show how the matrix develop over time - but in the same plot. The end result is sort of an animation. Any ideas as to how that is done ? The code below only produce one graph, and that is a picture of the very last updated matrix (matrix called abba, below).

Thank you in advance.

import numpy as np
import matplotlib.pyplot as plt

dimension = 3
abba = np.matrix( [ [2,5,2], [1,1000,4], [2,1,2] ] )

def sandpile(field):

    greater3 = np.where(field > 3)
    
    left = (greater3[0], greater3[1]-1)
    right = (greater3[0], greater3[1]+1)
    top = (greater3[0] - 1, greater3[1])
    bottom = (greater3[0]+1 , greater3[1])

    bleft   = left[0][np.where(left[1] >= 0)], left[1][np.where(left[1] >= 0)]
    bright  = right[0][np.where(right[1] < dimension)], right[1][np.where(right[1] < dimension)]
    btop    = top[0][np.where(top[0] >= 0)], top[1][np.where(top[0] >= 0)]
    bbottom = bottom[0][np.where(bottom[0] < dimension)], bottom[1][np.where(bottom[0] < dimension)]

    field[greater3] -= 4

    field[bleft] += 1
    field[bright] += 1
    field[btop] += 1
    field[bbottom] += 1
            
    return (field) 

print(abba)

matfig = plt.figure(figsize=(3,3))
plt.matshow(abba, fignum=matfig.number)

n = 0
while (abba < 4).all() == False:
    
    abba = sandpile(abba)
    
    plt.matshow(abba, fignum=matfig.number)
    
    n += 1

print('Exit with',n,'steps')
print(abba)

Upvotes: 0

Views: 55

Answers (1)

Mehdi Seifi
Mehdi Seifi

Reputation: 516

This is one way you can see an updating plot in a loop:

...

matfig = plt.figure(figsize=(3,3))
ax1 = matfig.add_subplot(1, 1, 1)
ax_image = ax1.imshow(abba)
plt.show(block=False)

n = 0
while (abba < 4).all() == False:

    abba = sandpile(abba)

    ax_image.remove()
    ax_image = ax1.imshow(abba)
    matfig.canvas.draw()
    matfig.canvas.flush_events()
    n += 1
    print(n)

print('Exit with',n,'steps')
print(abba)
plt.show(block=True)

In your example changes happens at the very end of the loop.

Upvotes: 1

Related Questions