Search code examples
pythonmatplotlibplotpython-xarraycartopy

AttributeError: 'AxesSubplot' object has no attribute 'coastlines'


ds_mm=gb.mean(dim='TIME')
ds_mm

Data description is given here: preview of xarray Dataset with one variable ILD_T05 with dimensions (month, LAT71_110, LON86_140)

ax= plt.axes(projection=ccrs.PlateCarree())
pp=ds_mm.ILD_T05
p=pp.plot.contourf(   
    x='LON86_140',
    y='LAT71_110',
    col='month',
    levels=30,
    col_wrap=3,
    cmap=plt.cm.rainbow,
)

for ax in p.axes.flat:
    ax.coastlines()

I am getting the contour plots correctly but while trying to add coastlines through a for loop it shows attribute error.

AttributeError                            Traceback (most recent call last)
c:\Users\souga\OneDrive\Desktop\Python programs\gb.ipynb Cell 8 in <cell line: 12>()
      3 p=pp.plot.contourf(   
      4     x='LON86_140',
      5     y='LAT71_110',
   (...)
      9     cmap=plt.cm.rainbow,
     10 )
     12 for ax in p.axes.flat:
---> 13     ax.coastlines()

AttributeError: 'AxesSubplot' object has no attribute 'coastlines'

Solution

  • You have not created the contour plots on axes with the cartopy projection. To do this, use the subplot_kws argument to xr.DataArray.plot, e.g.:

    pp=ds_mm.ILD_T05
    p=pp.plot.contourf(   
        x='LON86_140',
        y='LAT71_110',
        col='month',
        levels=30,
        col_wrap=3,
        cmap=plt.cm.rainbow,
        subplot_kws={'projection': ccrs.PlateCarree()},
    
    )