Python contour line plot#

Software requirements:

  • Python 3.x

  • Numpy

  • matplotlib

  • cartopy

  • xarray

Example script#

matplotlib_contour_lines.py

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

This example demonstrates how to plot colored contour lines on a map.

Content

- draw a map
- add coastlines, state borders and provinces, add gridlines
- draw colored contour lines
- add a colorbar
- save to PNG 

-------------------------------------------------------------------------------
2022 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 cartopy
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')

    plt.switch_backend('agg')

    #-- create figure and axes object
    fig, ax = plt.subplots(figsize=(12,12), subplot_kw=dict(projection=ccrs.PlateCarree()))

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

    #-- add coastlines, country border lines, and grid lines
    ax.coastlines()
    ax.add_feature(cfeature.BORDERS, linewidth=0.6, edgecolor='dimgray')
    ax.gridlines(draw_labels=True,
                 linewidth=0.5,
                 color='gray',
                 xlocs=range(-180,180,30),
                 ylocs=range(-90,90,30))

    #-- create contour line plot
    cnplot = ax.contour(ds.lon, ds.lat, ds.tsurf.isel(time=0),
                        linewidths=1.5,
                        cmap='jet',
                        levels=15,
                        transform=ccrs.PlateCarree())

    #-- add colorbar
    cbar = plt.colorbar(cnplot, pad=0.07, shrink=0.3)
    cbar.set_label('K')

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

if __name__ == '__main__':
    main()
    

Plot result#

Matplotlib contour lines example w400