Skip to content Skip to sidebar Skip to footer

Contour Plot Masked On The Basis Of Grid

I am trying to generate a contour plot based on (x,y) coordinates surface with a cube in it that dosent include any data z . Following is its scatterplot. I use the following cod

Solution 1:

The problem is in the meshgrid generation. The values in y go from 0 to 40 more than a dozen times. Thus, the generated xi and yi will be really unintuitive matrixes.

The proper way of generating the meshgrid is the following:

xi,yi = np.meshgrid(np.linspace(x.min(),x.max(),200),np.linspace(y.min(),y.max(),200))

Example

I have generated some data with a similar shape:

import scipy.signalas sgn
import scipy.interpolateas intr
import numpy.maas ma
x = np.linspace(-100,0,500)
y = sgn.sawtooth(2 * np.pi * .2 * x)
mask = (x>-50) & (x<-25)
y[mask] = (sgn.sawtooth(2 * np.pi * .2 * x[mask])+1)/2
y = (y+1)*25
plt.plot(x,y)
z = np.sin(2*np.pi*.1*x)+np.sin(2*np.pi*.1*y)

Such that the plot x vs y looks like:

sawtooth

The code you are actually using generates the following plot:

xi,yi = np.meshgrid(x,y)
mask =(yi> 0) & (yi< 25) & (xi > -53) & (xi < -25) 
zi = intr.griddata((x,y), z, (xi, yi) , method='cubic')
zi = ma.masked_array(zi, mask = mask )
plt.contourf( xi,yi,zi,100); plt.colorbar()

bad contourf

The interpolation to obtain the grid data yields unexpected and incorrect results, which result in the obtained contourf. In fact, plotting plt.imshow(mask) reveals the positions in the matrix where the values inside the square (y > 0) & (y < 25) & (x > -53) & (x < -25) are placed in the matrix.

mask imshow

When the meshgrid is defined as proposed, the result is this one instead:

enter image description here

Post a Comment for "Contour Plot Masked On The Basis Of Grid"