Python matplotlib example contour line plot#
Software requirements:
Python 3.x
Numpy
matplotlib
cartopy
xarray
Run the contour lines example script:
python matplotlib_contour_lines.py
Script matplotlib_contour_lines.py:
"""
DKRZ matplotlib script: matplotlib_contour_lines.py
- contour lines over map plot
- rectilinear grid (lat/lon)
- colorbar
08.02.21 meier-fleischer(at)dkrz.de
"""
import cartopy
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')
#-- 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()
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))
#-- add title
ax.set_title('Temperature', fontsize=10, fontweight='bold')
#-- create contour line plot
cnplot = ax.contour(ds.lon, ds.lat, ds.tsurf[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()