Example: Contour plot with streamlines
In this example, we’ll plot a tracer field from CAM and overlay streamlines showing the flow.
%matplotlib inline
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
Load the dataset
ds = xr.open_dataset('../data/co2.nc')
ds
Convert units
mwair = 28.966
mwco2 = 44.
with xr.set_options(keep_attrs=True):
ds['CO2'] = ds.CO2 * 1.0e6 * mwair / mwco2
ds.CO2.attrs['units'] = 'ppm'
Make the plot
fig = plt.figure(figsize=(12, 12))
# create axis with subplot a project
crs_latlon = ccrs.PlateCarree()
ax = fig.add_subplot(1, 1, 1, projection=crs_latlon)
ax.set_extent([-180, 180. , -85, 0], crs=crs_latlon)
ax.coastlines('50m')
# plot CO2
field, lon = add_cyclic_point(ds.CO2, coord=ds.lon)
cf = ax.contourf(lon, ds.lat, field,
levels=np.arange(391, 406.5, 0.5),
cmap='RdYlBu_r',
extend='both',
transform=ccrs.PlateCarree())
# plot velocity field
uvel, lonu = add_cyclic_point(ds.U, coord=ds.lon)
vvel, lonv = add_cyclic_point(ds.V, coord=ds.lon)
lonu = np.where(lonu>=180.,lonu-360.,lonu)
sp = ax.streamplot(lonu, ds.lat, uvel, vvel,
linewidth=0.2,
arrowsize = 0.2,
density=5,
color='k',
transform=ccrs.PlateCarree())
# add colorbar
cb = plt.colorbar(cf,orientation='horizontal', pad=0.04, aspect=50)
cb.ax.set_title('CO$_2$ [ppm]');