Python matplotlib example contour filled plot#

Software requirements:

  • Python 3

  • Numpy

  • matplotlib

  • cartopy

  • xarray

Run the filled contour example script:

python matplotlib_contour_filled.py

Script matplotlib_contour_filled.py:

    """
    DKRZ matplotlib script:  matplotlib_contour_filled.py

       - filled contour over map plot
       - rectilinear grid (lat/lon)
       - colorbar

       08.02.21  meier-fleischer(at)dkrz.de
    """
    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('/Users/k204045/Python/DKRZ_Python_Workshop/material/data/rectilinear_grid_2D.nc')

            #-- create figure and axes object
            fig = plt.figure(figsize=(12,12))

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

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

            #-- 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=2)
            ax.add_feature(states_provinces, edgecolor='gray', zorder=3)

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

            #-- add title
            ax.set_title('Temperature', fontsize=12, fontweight='bold')

            #-- 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.05, shrink=0.7)
            cbar.set_label('K')

            #-- save graphic output to PNG file
            plt.savefig('plot_matplotlib_contour_filled_rect.png',
                        bbox_inches='tight',
                        dpi=100)

if __name__ == '__main__':
    main()

Plot result#

Matplotlib contour filled example w400