import wrf
from netCDF4 import Dataset
import proplot as plot
import cartopy.crs as crs
# Download the dataset from https://www.unidata.ucar.edu/software/netcdf/examples/wrfout_v2_Lambert.nc
# Load the dataset
ncfile = Dataset('wrfout_v2_Lambert.nc')
# Get the variable
slp = wrf.getvar(ncfile, "slp")
# Get the latitude and longitude points
lats, lons = wrf.latlon_coords(slp)
# Get the cartopy mapping object
cart_proj = wrf.get_cartopy(slp)
#Plotting
fig, axs = plot.subplots(proj=cart_proj)
# Define extents
lat = [lats.min(), lats.max()]
lon = [lons.min(), lons.max()]
#format the plot
axs.format(
lonlim=lon, latlim=lat,
labels=True, innerborders=True
#Plot using contourf
m = axs.contourf(wrf.to_np(lons), wrf.to_np(lats), wrf.to_np(slp),
transform=crs.PlateCarree(), cmap='roma_r')
#Adding colorbar with label
cbar = fig.colorbar(m, loc='b', label='Sea Level Pressure (hPa)')
#Saving the figure
fig.savefig('slp.png')
Output
Explanation
Basic import stuff for Python
import wrf
from netCDF4 import Dataset
import proplot as plot
import cartopy.crs as crs
Loading the dataset
ncfile = Dataset('wrfout_v2_Lambert.nc')
Extracting the varibale of your choice. Here it is sea level pressure (SLP).
slp = wrf.getvar(ncfile, "slp")
Get the lat/lon and projection of the WRF file. Here the projection is LCC.
lats, lons = wrf.latlon_coords(slp)
cart_proj = wrf.get_cartopy(slp)
Create the plot and define projection using proj
.
fig, axs = plot.subplots(proj=cart_proj)
Setting up the extent of the plot by getting the maximum and minimum lat and long.
lat = [lats.min(), lats.max()]
lon = [lons.min(), lons.max()]
Format the plot aesthetics.
axs.format(
lonlim=lon, latlim=lat,
labels=True, innerborders=True
Plot the filled contour of the variable.
m = axs.contourf(wrf.to_np(lons), wrf.to_np(lats), wrf.to_np(slp),
transform=crs.PlateCarree(), cmap='roma_r')
Adding the colorbar at the bottom of the plot.
cbar = fig.colorbar(m, loc='b', label='Sea Level Pressure (hPa)')
Finally, saving the figure.
fig.savefig('slp.png')
If you do not like the LCC projection then you can change the following line:
fig, axs = plot.subplots(proj='cyl')
Output