首页 > 解决方案 > XARRAY 等高线图 AttributeError: Contourf

问题描述

我正在尝试使用 NCEP Reanalysis netcdf4 数据在全局地图上以等高线形式绘制 xarray 变量。我使用 xarray 计算变量“slp”的标准化异常,方法是将当月的 2 月与 2016-2019 年 2 月的平均值进行比较。我能够获得最终变量(stdn”作为 xarray.core.dataset。但是,我的错误消息如下,我已将 matplotlib 更新到当前版本 3.2。我一直在搜索此错误,但没有任何帮助。谢谢你!我的代码如下,我不断收到这个错误 - AttributeError:'_Dataset_PlotMethods'对象没有属性'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()

或者,我已经尝试过了,但出现以下错误:

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

ValueError: Dataset.plot 不能直接调用。使用显式绘图方法,例如 ds.plot.scatter(...)

标签: pythonmatplotlibcontourpython-xarray

解决方案


为了充分利用 xarray 的绘图功能,最好DataArraystdn一开始就提取底层!然后你就可以做da_stdn.plot(),它应该可以正常工作。


推荐阅读