user2100039
user2100039

Reputation: 1366

XARRAY Contour Plot AttributeError: Contourf

I am trying to plot a xarray variable in contour form on a global map using the NCEP Reanalysis netcdf4 data. I calculate using xarray the standardized anomaly for the variable "slp" by comparing the Feb of the current month with the average of the last years February's from 2016-2019. I am able to obtain a final variable (stdn" as a xarray.core.dataset. However, my error message is as follows and I have updated matplotlib to the current version 3.2. I've been searching this error with no help. Thank you! My code is follows and I keep getting this error - AttributeError: '_Dataset_PlotMethods' object has no attribute 'contourf'.

from sys import exit
import netCDF4 as nc4
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap, cm
import datetime 
import pandas as pd
import xarray as xr
import bottleneck as bn
import cartopy.crs as ccrs

#The easiest way to read the data is:
path = "//porfiler03/gtdshare/IDL/wtypes/data/slp.2020.nc"
DSC = xr.open_mfdataset(path,combine='nested',concat_dim='time')
DSC = DSC.sel(time=slice('2020-02-01','2020-02-29'))
damc = DSC.groupby('time.month').mean(dim='time')#current year/month Feb 2020 mean slp

mfdataDIR = "//porfiler03/gtdshare/IDL/wtypes/data/avgyears/*.nc"
DS = xr.open_mfdataset(mfdataDIR,combine='nested',concat_dim='time')
da = DS.slp.ffill(dim='time')
da = da.sel(time=slice('2016-01-01','2019-12-31'))
dam = da.groupby('time.month').mean(dim='time')# monthly mean of 2016-2019 dim 12x73x144
damcm = dam.sel(month=slice('2'))#current month mean slp
dams = da.groupby('time.month').std(dim='time')#
damscm = dams.sel(month=slice('2'))#current month stdev slp

stdn = (damc - damcm)/ damscm#standard normal for Feb 2020 
#
stdn.plot.contourf()

exit()

# same error using the below code
ax = plt.axes(projection=ccrs.Orthographic(-80, 35))
ax.set_global()
stdn.plot.contourf(ax=ax, transform=ccrs.PlateCarree())
ax.coastlines()

Or, I have tried this and I get the following error:

stdn.plot(robust=True, figsize=(10,6))

ValueError: Dataset.plot cannot be called directly. Use an explicit plot method, e.g. ds.plot.scatter(...)

Upvotes: 1

Views: 5380

Answers (1)

Andrew Williams
Andrew Williams

Reputation: 781

To make the most out of xarray's plotting functionality, it's best to extract the underlying DataArray from stdn first! Then you'll be able to just do da_stdn.plot() and it should work fine.

Upvotes: 3

Related Questions