error "Input z must be 2D, not 3D" related to plot nc file in python

37 Views Asked by At

I used 500 hPa NOAA Reanalysis Version 3 to plot the mean anomaly of vertical velocity during a specific period (https://www.psl.noaa.gov/mddb2/makePlot.html?variableID=142267). I got the "input z must be 2D, not 3D" error when the following code was used:

from netCDF4 import Dataset as NetCDFFile 
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
fig = plt.figure(figsize=(10,9), constrained_layout=True ) 
ax = fig.add_subplot(111).set_title('b1' , size=10 , fontweight='bold') #(nrow , ncol ,nfig)
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0 )
nc1 = NetCDFFile('C:/Users/user/Desktop/project/nc2024Habib/final-mjo/obs1-vv-ac.nc')
lat = nc1.variables['lat'][:]
lon = nc1.variables['lon'][:]
#z=nc1.variables['level'][0]
omega = nc1.variables['omega'][:]
map= Basemap    (projection='merc',llcrnrlon=0.,llcrnrlat=10.,urcrnrlon=80.,urcrnrlat=45.,resolution='i',fix_aspect=False)  
map.drawcoastlines()
map.drawstates()
map.drawcountries()
map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF')
map.drawcounties() 
parallels = np.arange(15.,45.,5.)
meridians = np.arange(30.,70.,5.)
map.drawparallels(parallels,labels=[1,0,0,0],fontsize=10 , linewidth=0.9,dashes=[4,9900], fontweight='bold' ,fontstyle='oblique')
map.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10, linewidth=0.9,dashes=[4,9900] , fontweight='bold', fontstyle='oblique')
lons,lats= np.meshgrid(lon-180,lat )
X,Y = map(lons,lats)
clevs1 = np.arange(-0.02,0.01,0.005)
cs1 = map.contourf(X,Y, omega[0,:,:],clevs1,cmap='RdBu_r')
plt.show()

I would be grateful if someone could help me to fix this error

1

There are 1 best solutions below

5
Bart On

Print omega[0,:,:].ndim or omega[0,:,:].shape; It is going to be a 3-dimensional array (as the error says), while you should pass a 2D array to contourf().

I just checked; omega has dimensions (time, level, lat, lon), so you have to slice off one more dimension using e.g.:

cs1 = map.contourf(X, Y, omega[0,0,:,:], clevs1, cmap='RdBu_r')

To plot the first time step and first height level.