I have a meshgrid given by X and Y of unequal length and a 2d array of values vx2. I want to create a sub-2d array Z from a certain xlim and ylim. I want to create a contour plot but since matplotlib only zooms into this region and doesn't rescale the contour levels to these values. But I am failing at this:
This is the code snippet. x and y are predefined coordinate arrays. vx2_d has shape (len(x),len(y)).
X, Y = np.meshgrid(x, y)
mask_x = (x >= 60) & (x <= 61.2)
mask_y = (y >= 1.42) & (y <= 1.72)
# have to convert to numpy since I can't figure out how to create a 2d list from 2 1d lists.
mask_x_r = np.array(mask_x)[:,np.newaxis]
mask_y_r = np.array(mask_y)[np.newaxis,:]
# Combine the masks
# For some reason a simple mask_x_r * mask_y_r just gives me a 1D array.
mask = np.multiply(mask_x_r,mask_y_r )
mask = np.reshape(mask,(len(mask_x),len(mask_y)))
Za_subregion = vx2_d[mask.tolist()]
# A simple Za_subregion = vx2_d[mask_x][mask_y] gives an error about shape not being broadcastable
print(np.shape(Za_subregion))
plt.pcolormesh(X[mask_x],Y[mask_y],Za_subregion.T,cmap=plt.cm.seismic)
#plt.pcolormesh(X,Y,vx2_d.T,cmap=plt.cm.seismic)
plt.xlabel("Radial distance")
plt.ylabel("Angular distance")
plt.title("Dust Vx2 Contour plot")
plt.colorbar()
#plt.xlim(60,61.2)
#plt.ylim(1.42,1.72)
plt.show()
Unfortunately print(np.shape(Za_subregion)) just gives me a 1d array and the whole plot naturally throws an error. What can I do fix/improve this?
x,yorvx2_dare. And we can't even surmise, since the affirmation you make in comments are unreproducible (mask_x_r*mask_y_rdoes produce a 2D array, not 1D, for example). Also, we can't really understand why you say that you are "forced to convert to numpy", when everything we see here is already 100% numpy. Nor why to usemask.tolist()to index that mysteriousvx2_d. Anyway, that is not a guessing game. Please provide a minimal reproducible example and all information we needmask_x = (X >= 60) & (X <= 61.2), which will give you a 2D mask (same forY) and then combine the masks asmask = mask_x & mask_y. Thatmaskresult can be used to indexX,Y, andvx2_d(assumingvx2_dis a 2D array). Alternatively, you can use your currentmask_xandmask_ydefinitions and then createmask = mask_x[None,:] & mask_y[:,None].