Search code examples
pythonmatplotlibnetcdfpython-xarrayimshow

How to get country border lines while plotting with imshow in python


I am trying to plot seasonal mean from a netcdf file using xarray and matplotlib. I am getting the plots with latitude and longitude axes but there is no country border line. How to obtain country border lines on the plots.

import xarray as xr
import matplotlib as mpl
import matplotlib.pyplot as plt

fname='/home/atmosphere/data/outputs/2010.nc'         #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

ds=xr.open_mfdataset(fname)
varlist=list(ds.variables)
imr=ds.sel(lat=slice(0,35),lon=slice(60,100)) #subsetting overthe region
imrbt=imr['temp']                             #making into a data array  
ds['time.season']

seasonal=imrbt.groupby('time.season').mean(dim='time')
seasonal.plot.imshow(col='season',robust=True)

Solution

  • As @Bart mentioned, you have to use [cartopy][1] to solve this issue:

    import cartopy.crs as ccrs
    air = xr.tutorial.open_dataset('air_temperature').air
    ax = plt.axes(projection=ccrs.Orthographic(-80, 35))
    seasonal.plot.contourf(ax=ax, transform=ccrs.PlateCarree())
    ax.add_feature(cartopy.feature.BORDERS)
    ax.coastlines()
    

    To add country borders in higher resolution you have to use cartopy features:

    import cartopy.feature as cfeature
    
    country_borders = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_0_boundary_lines_land',
        scale='50m',
        facecolor='none')
    ax.add_feature(country_borders, edgecolor='gray')