Python matplotlib example vectors on contour plot#

Software requirements:

  • Python 3

  • matplotlib

  • cartopy

  • numpy

  • xarray

Run the vectors on contour example script:

python matplotlib_vector_on_contour.py

Script matplotlib_vector_on_contour.py:

"""
DKRZ matplotlibscript:  matplotlib_vector_on_contour.py

   - vectors on filled contour map plot
   - rectilinear grid (lat/lon)

   08.02.21  meier-fleischer(at)dkrz.de
"""
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

def main():

        #-- open netcdf file
        ds = xr.open_dataset('rectilinear_grid_2D.nc')

        fig = plt.figure(figsize=(12,6))

        #-- choose map projection
        ax = plt.axes(projection=ccrs.PlateCarree())

        #-- add coastlines, country border lines, and grid lines
        ax.coastlines(zorder=5)

        ax.set_title('Wind velocity and temperature', fontsize=12, fontweight='bold')

        #-- create states outlines
        states_provinces = cfeature.NaturalEarthFeature(category='cultural',
                                    name='admin_1_states_provinces_lines',
                                    scale='50m', facecolor='none')
        ax.add_feature(cfeature.BORDERS, linewidth=0.6, edgecolor='gray', zorder=1)
        ax.add_feature(states_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))

        #-- create contour line plot
        cnplot = ax.contourf(ds.lon, ds.lat, ds.tsurf[0,:,:],
                             cmap='jet',
                             levels=15,
                             zorder=0,
                             transform=ccrs.PlateCarree())

        #-- add colorbar
        cbar = plt.colorbar(cnplot, orientation='horizontal', pad=0.1, shrink=0.6)
        cbar.set_label('K')

        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())

        vref = ax.quiverkey(vplot, 0.79, 0.25, 20,
                            r'$20 \frac{m}{s}$',
                            labelpos='E',
                        coordinates='figure', zorder=5)


        plt.savefig('plot_matplotlib_vector_on_contour_rect.png', bbox_inches='tight',
                     dpi=100)

if __name__ == '__main__':
    main()

Plot result:#

image0