Question

I would like to visualize the magnitude of VM with respect to time t. In the following program, t is set to zero. I would appreciate it if one could tell me how to produce an animation of the bilinear interpolation contour plot. Thank you! Please here is the code:

import numpy as np
from numpy import cos, sin, pi, exp, sqrt
from matplotlib import pyplot as plt
import matplotlib.cm as cm

nx=30
ny=30

nu=0.0025
p=2*pi

x = np.linspace(0,p,nx)
y = np.linspace(0,p,ny)

fig,ax = plt.subplots(1,1)
ax.set_xlim(0,p)
ax.set_ylim(0,p)

t=0
X,Y = np.meshgrid(x,y)
U=-cos(X)*sin(Y)*exp(-2*nu*t)
V=sin(X)*cos(Y)*exp(-2*nu*t)
VM=sqrt(U**2+V**2)

im = plt.imshow(VM, interpolation='bilinear', origin='lower',
            cmap=cm.gray, extent=(0, p, 0, p))
levels = np.arange(-1.2, 1.6, 0.2)

# add a vertical colorbar.
CBI = plt.colorbar(im, orientation='vertical', shrink=0.8)
plt.show()
Was it helpful?

Solution

mostly copied from here. See there for in depth explanations.

import numpy as np
from numpy import cos, sin, pi, exp, sqrt
from matplotlib import pyplot as plt
import matplotlib.cm as cm
from matplotlib import animation

nx=30
ny=30

nu=0.0025
p=2*pi

x = np.linspace(0,p,nx)
y = np.linspace(0,p,ny)

fig,ax = plt.subplots(1,1)
ax.set_xlim(0,p)
ax.set_ylim(0,p)

t=0
X,Y = np.meshgrid(x,y)
U=-cos(X)*sin(Y)*exp(-2*nu*t)
V=sin(X)*cos(Y)*exp(-2*nu*t)
VM=sqrt(U**2+V**2)

im = plt.imshow(VM, interpolation='bilinear', origin='lower',
            cmap=cm.gray, extent=(0, p, 0, p))
levels = np.arange(-1.2, 1.6, 0.2)

# add a vertical colorbar.
CBI = plt.colorbar(im, orientation='vertical', shrink=0.8)


def init():
    im.set_data((np.empty_like(VM)))
    return im,

def animate(t):
    U=-cos(X)*sin(Y)*exp(-2*nu*t)
    V=sin(X)*cos(Y)*exp(-2*nu*t)
    VM=sqrt(U**2+V**2)
    im.set_data(VM)
    return im,

# # call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

plt.show()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top