Animation Interpolation Python Matplotlib - python

I would like to make an animation of an interpolation.
This is my code for the moment :
import scipy.interpolate as itp
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
def update(i,Z):
x = np.arange(0,Z.shape[0])
y = np.arange(0,Z.shape[0])
I = itp.interp2d(x, y, Z, kind='cubic')
xi = np.linspace(0, Z.shape[0]-1, Z.shape[0]+1)
yi = np.linspace(0, Z.shape[0]-1, Z.shape[0]+1)
Z = I(xi, yi)
return Z
Z = np.random.randint(10, size=(4, 4))
fig, ax = plt.subplots()
matrice = ax.matshow(Z)
plt.colorbar(matrice)
ani = animation.FuncAnimation(fig, update, frames=19, interval=500,fargs=(Z,))
fig.show()
So as you can see, I want to show the progress of the interpolation, but it doesn't work. Z matrix never changes.
Can you help me please.
Thank you in advance.

Thank you for you help. I managed to to solve my problem :
import scipy.interpolate as itp
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
def update(i,Z,size_initial):
x = np.arange(0,size_initial)
y = np.arange(0,size_initial)
I = itp.interp2d(x, y, Z, kind='cubic')
xi = np.linspace(0, size_initial-1, i+size_initial)
yi = np.linspace(0, size_initial-1, i+size_initial)
Z = I(xi, yi)
matrice.set_data(Z)
return matrice,
size_initial = 4
Z = np.random.randint(100, size=(size_initial, size_initial))
fig, ax = plt.subplots()
matrice = ax.matshow(Z)
plt.colorbar(matrice)
ani = animation.FuncAnimation(fig, update, frames=50, interval=500,fargs=[Z,size_initial])
fig.show()

Related

How to normalize colorbar in Python?

I want to adjust colobar scale from my current figure1 to the desired figure2 !!
My colorbar scale range is -1 to 1, but I want it in exponential form and for that I tried levels = np.linspace(-100e-2,100e-2) as well, but it also doesn't give the desired scale2
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
ds = xr.open_dataset('PL_Era_Tkt.nc')
wp = ds.w.mean(dim=['longitude','latitude']).plot.contourf(x='time',cmap='RdBu',add_colorbar=False,extend='both')
wpcb = plt.colorbar(wp)
wpcb.set_label(label='Pa.s${^{-1}}$',size=13)
plt.gca().invert_yaxis()
plt.title('Vertical Velocity',size=15)
My current scale
My desired scale
Since the data is not presented, I added normalized color bars with the data from the graph sample here. I think the color bar scales will also be in log format with this setup. Please note that the data used is not large, so I have not been able to confirm this.
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as ticker
import numpy as np
plt.style.use('seaborn-white')
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig, ax = plt.subplots()
ax.contourf(X, Y, Z, 20, cmap='RdGy')
cmap = mpl.cm.RdGy
norm = mpl.colors.Normalize(vmin=-1, vmax=1.0)
fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
ax=ax, orientation='vertical', label='Some Units', extend='both', ticks=ticker.LogLocator())
plt.show()

How to add correlation coefficient (R^2) in line chart?

I want to add R^2 and R in my line chart.But I just know how to add equation in the chart.Here is my code.Thanks a lot!
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from sympy import S, symbols, printing
import pylab as pl
# Data for plotting
y = df["rain"]
x = df["SITE"]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(xlabel='year', ylabel='P',
title='rain')
ax.grid()
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
pylab.plot(x,p(x),"y--")
pl.plot(x, y, 'og-', label=("y=%.6fx+(%.6f)"%(z[0],z[1])))
pl.legend()

Paraboiloid from an array elements python

Please help with the problem of paraboloid 3d plotting using from the elements in an array.
Below code gives a nice parabolid:
from matplotlib import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
import math
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
a=2
t = np.arange(0, 1, 0.01)
th = np.arange(0, 2*pi, 0.01)
t,th = np.meshgrid(r, T)
#Parametrise it
X = r*cos(T)
Y = r*sin(T)
Z = a*r**2
ax.plot_surface(X, Y, Z, alpha=0.9, rstride=10, cstride=10, linewidth=0.5, cmap=cm.summer)
plt.show()
But I want something like this:
th,t,a = symbols('th t a')
rotz=np.matrix([[cos(th),-sin(th),0,0],
[sin(th),cos(th),0,0],
[0,0,1,0],
[0,0,0,1]])
g=np.matrix([t,0,a*(t**2),1])
g=np.transpose(g)
M = rotz*g
print(M)
Now M is a 4x1 matrix with the 1st three elements to parametrize the paraboloid code
[[t*cos(th)]
[t*sin(th)]
[a*t**2]
[1]]
Now I want to use the x=M[0,:],y=M[1,:],z=M[2,:] and replace it in the parabolid code and plot the paraboloid.
I want this way so that I could do some transformation to the matrix as needed.

Converting a 2D figure into a cylinder in Python

At the moment I have a figure that looks like this,
Generated by the code:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(20,5)
rows,cols = data.shape
plt.imshow(data, interpolation='nearest', extent=[0.5, 0.5+cols, 0.5, 0.5+cols], cmap='bwr')
plt.show()
However I would like to 'fold' this up into a 3D cylinder, joining the left and right edges (as one would do with a sheet of paper). In other words the left edge and the right edges are actually the same edge and so I would like to join them together to form a cylinder.
How would I go about doing this?
The Poly3DCollection is the method of choice for arbitrary 3D polygons in mplot3d.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
nphi,nz=12,20
r=1 # radius of cylinder
phi = np.linspace(0,360, nphi)/180.0*np.pi
z= np.linspace(0,1.0,nz)
print z
facecolors=['r','g','b','y']
cols=[]
verts2 = []
for i in range(len(phi)-1):
cp0= r*np.cos(phi[i])
cp1= r*np.cos(phi[i+1])
sp0= r*np.sin(phi[i])
sp1= r*np.sin(phi[i+1])
for j in range(len(z)-1):
z0=z[j]
z1=z[j+1]
verts=[]
verts.append((cp0, sp0, z0))
verts.append((cp1, sp1, z0))
verts.append((cp1, sp1, z1))
verts.append((cp0, sp0, z1))
verts2.append(verts)
value=np.random.rand()
print value
col=plt.cm.bwr(value)
print col
cols.append(col)
poly3= Poly3DCollection(verts2, facecolor=cols )
poly3.set_alpha(0.8)
ax.add_collection3d(poly3)
ax.set_xlabel('X')
ax.set_xlim3d(-1, 1)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 1)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
plt.show()
You could use plot_surface:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
np.random.seed(2016)
data = np.random.rand(12, 20)
h, w = data.shape
theta, z = np.linspace(0, 2 * np.pi, w), np.linspace(0, 1, h)
THETA, Z = np.meshgrid(theta, z)
X = np.cos(THETA)
Y = np.sin(THETA)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
cmap = plt.get_cmap('bwr')
plot = ax.plot_surface(
X, Y, Z, rstride=1, cstride=1, facecolors=cmap(data),
linewidth=0, antialiased=False, alpha=0.75)
plt.show()
yields

Python animate contour plot for function generated in for loops

I have a three-variable function myfunc that is generated inside three for loops. I want to draw a contour plot of y vs x and animate this for different times t. However, I've looked at the various matplotlib examples on the webpage, and am still unsure of how to do this.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import animation
def myfunc(x,y,t):
w = 0.5*x + y + 4*np.sin(1.8*t)
return w
xlist = np.linspace(0,10,10)
ylist = np.linspace(-1,1,10)
tlist = np.linspace(0,50,50)
plt.figure()
for t in tlist:
for x in xlist:
for y in ylist:
w = myfunc(x,y,t)
w_vec = np.array(w)
w_contour = w_vec.reshape((xlist.size, ylist.size))
w_plot = plt.contourf(ylist,xlist,w_contour)
plt.xlabel('x', fontsize=16)
plt.ylabel('y', fontsize=16)
plt.show()
Edit: I quite like the look of dynamic_image2.py in this tutorial. This seems to get things moving, but the axes are wrong:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x,y,t):
return 0.5*x + np.sin(y) + 4*np.sin(1.8*t)
x = np.linspace(0, 10, 10)
y = np.linspace(-1, 1, 10).reshape(-1, 1)
tlist = np.linspace(0,50,50)
ims = []
for t in tlist:
x += np.pi / 15.0
y += np.pi / 20.0
im = plt.imshow(f(x,y,t))
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=20, blit=True,
repeat_delay=1000)
plt.show()

Categories