0

Here I have made a simple program, which populate a 2-D mesh by taking values from a matrix(NxN) 'config' which has random values from (-1 to 1). I want this plot to be animated so that when I update these values in Matrix the plots gets updated. I have seen few animation codes ,but the are not what I am looking. Can someone point me to right direction. Thank You.

import numpy as np
from numpy.random import rand
import matplotlib.pyplot as plt
import matplotlib.animation as animation

f = plt.figure(figsize=(15, 15), dpi=80);
N=10
n_=1
i=1

config = 2*np.random.uniform(2, size=(N,N))-3
print(config)

X, Y = np.meshgrid(range(N), range(N))
#print(X)

plt.pcolormesh(X, Y, config, cmap=plt.cm.RdBu);
plt.title('Time=%d' % i);
plt.axis('tight')
plt.show()

We can make a new matrix/tensor "animate_grid" with (TxNxN), i.e. NxN matrix of updated value(any values even random) for each time step T. example

 T=0 
[[-0.244608 -0.71395497 -0.36534627]  
[-0.44626849 -0.82385746 -0.74654582]
[ 0.38240205 -0.58970239  0.67858516]]
T=1
[[-0.46084 -0.3413957 -0.3453345627]
[-0.43626849 -0.6385746 -0.4654582]
[ 0.8240205 -0.8970239  0.37858516]]
T=2 
[[-0.4546084 -0.9565497 -0.534627]
[-0.2546849 -0.8345746 -0.465654582]
[ 0.4460205 -0.4660239  0.6858516]]

etc. etc.

2
  • Could you explain more in detail which other answers have not helped you and in how far they did not? Could you also explain more in detail what you expect your code to produce? How would you change the matrix? Please do so by editing your question. Commented May 6, 2017 at 13:02
  • We can make a new matrix/tensor "animate_grid" with (TxNxN), i.e. NxN matrix of updated value(any values even random) for each time step T. Commented May 6, 2017 at 13:50

1 Answer 1

1

The animation would work just as in any other case. You need a function that updates the plot and an instance of FuncAnimation which calls this updating function regularly.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
N=10
T=17
config = np.random.rand(T, N,N)
X, Y = np.meshgrid(range(N+1), range(N+1))

fig = plt.figure(figsize=(5, 5), dpi=80)
plt.pcolormesh(X, Y, config[0,:,:], cmap=plt.cm.RdBu)
plt.title('Time=%d' % 0)

def update(i):
    plt.pcolormesh(X, Y, config[i,:,:], cmap=plt.cm.RdBu)
    plt.title('Time=%d' % i)

ani = animation.FuncAnimation(fig, update, frames=config.shape[0], 
                              interval = 100, repeat = True)

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!!! This is exactly what I was looking for. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.