Python vectors on contour plot#

Software requirements:

  • Python 3

  • matplotlib

  • cartopy

  • numpy

  • xarray

Example script#

matplotlib_vector_on_contour.py

#!/usr/bin/env python
# coding: utf-8
'''
DKRZ example

Plot color filled contours on a map with vectors overlaid on it.

Content
- draw map
- draw coastlines, state borders and provinces
- draw filled contours
- draw vectors
- save to PNG

-------------------------------------------------------------------------------
2021 copyright DKRZ licensed under CC BY-NC-SA 4.0 <br>
               (https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en)
-------------------------------------------------------------------------------
'''
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

def main():
    #-- open netcdf file
    ds = xr.open_dataset('../../data/rectilinear_grid_2D.nc')
    
    #-- get states outlines
    provinces = cfeature.NaturalEarthFeature(category='cultural',
                                             name='admin_1_states_provinces_lines',
                                             scale='50m', 
                                             facecolor='none')
                                             
    #-- create the figure
    plt.switch_backend('agg')
    
    fig, ax = plt.subplots(figsize=(12,6), subplot_kw=dict(projection=ccrs.PlateCarree()))
    
    ax.set_title('Wind velocity and temperature', fontsize=12, fontweight='bold')
    
    #-- add coastlines, country border, provinces, and grid lines
    ax.coastlines(zorder=5)
    ax.add_feature(cfeature.BORDERS, linewidth=0.6, edgecolor='gray', zorder=1)
    ax.add_feature(provinces, edgecolor='gray', zorder=2)
    ax.gridlines(draw_labels=True,
                 linewidth=0.5,
                 color='gray',
                 zorder=3,
                 xlocs=range(-180,180,30),
                 ylocs=range(-90,90,30))
    
    #-- plot filled contours
    cnplot = ax.contourf(ds.lon, ds.lat, ds.tsurf.isel(time=0),
                         cmap='jet',
                         levels=15,
                         zorder=0,
                         transform=ccrs.PlateCarree())
    
    #-- add a colorbar
    cbar = plt.colorbar(cnplot, orientation='horizontal', pad=0.1, shrink=0.6)
    cbar.set_label('K')
    
    #-- plot vectors; thin out every other vector
    vplot = ax.quiver(ds.lon[::2], ds.lat[::2],
                      ds.u10[0,::2,::2],
                      ds.v10[0,::2,::2],
                      scale_units='xy',
                      scale=2.5,
                      angles='xy',
                      transform=ccrs.PlateCarree())
    
    #-- add vector reference annotation
    vref = ax.quiverkey(vplot, 0.79, 0.25, 20,
                        r'$20 \frac{m}{s}$',
                        labelpos='E',
                        coordinates='figure', zorder=5)
    
    #-- save to PNG file
    plt.savefig('plot_matplotlib_vector_on_contour_rect.png', bbox_inches='tight', dpi=100)


if __name__ == '__main__':
    main()

Plot result:#

image0