Plot winds vector from netcdf using python

Viewed 3752

I am currently working in internship on atmospheric/climate physics. I have netcdf datas from ERA5 (copernicus) that I already plotted in different maps, graphics etc... I need to plot wind vector with cartopy or anything else except basemap, but I can't figure it out.

This part of my script look like this right now :

import xarray as xr
from netCDF4 import Dataset as NetCDFFile 
import matplotlib.pyplot as plt
import numpy as np

import cartopy
import cartopy.feature as cfeat
import cartopy.crs as ccrs

ncw = xr.open_dataset('D:\Stage_IGE_CNRS\ERA5.nc')
nc2 = ncw.sel(time = slice('2016-03-06T06:00:00', '2016-03-31T18:00:00'), level = 1000).mean('time')
    
u = nc2['u']
v = nc2['v']
lon = nc2['longitude']
lat = nc2['latitude']

Thanks for your help.

Thomas V.

2 Answers

If you want to plot wind vectors, you're looking for quiver() from matplotlib (CartoPy just provides a projection-aware version):

import cartopy.crs as ccrs
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=ccrs.LambertConformal())
ax.quiver(lon, lat, u, v, transform=ccrs.PlateCarree())

If you wanted wind barbs, then you would use barbs()

We pass ccrs.PlateCarree() because it seems like your data are in lon/lat space. This implies that your wind components are earth relative in this case. When calling quiver/barbs, cartopy assumes that your coordinates (i.e. x/y or lon/lat) are in the same coordinate system as your vector components (i.e. u/v).

For a specific time in a general netcdf file:

import xarray
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np

ds = xarray.open_dataset("1988.nc")

u=ds.variables['u10'][:]
v=ds.variables['v10'][:]
lon=ds.variables['longitude'][:]
lat=ds.variables['latitude'][:]

lon2D, lat2D = np.meshgrid(lon, lat)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.quiver(lon2D, lat2D, u[0,:,:], v[0,:,:]) * insteadt of "0" put any time necessary
Related