Python matplotlib example vector plot#

Software requirements:

  • Python 3

  • matplotlib

  • cartopy

  • numpy

  • xarray

Run the vector example script:

python matplotlib_vectors.py

Script matplotlib_vectors.py:

"""
DKRZ matplotlib script:  matplotlib_vectors.py

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

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

def main():

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

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

        ax = plt.axes(projection=ccrs.PlateCarree())

        ax.coastlines(resolution='50m', linewidth=0.3, color='black')

        ax.gridlines(draw_labels=True, linewidth=0.5, color='gray',
                     xlocs=range(-180,180,30), ylocs=range(-90,90,30))

        ax.set_title('Wind velocity', fontsize=10, fontweight='bold')

        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.9, 0.905, 20,
                            r'$20 \frac{m}{s}$',
                            labelpos='E',
                        coordinates='figure', zorder=5)

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


if __name__ == '__main__':
    main()

Plot result:#

image0