使用 xarray 绘制 netCDF,数据未显示但图例显示

Plotting netCDF with xarray, data not showing but legend is

我正在尝试在 atmospheric composition analysis group.

的 netCDF 文件上使用 xarray 中的简单 .plot() 函数

假设我想绘制 2000 年北美的 PM2.5 浓度可用 here

当我尝试绘制数据集时,我得到一个空图,即使数据存在,如图例栏所示。

import xarray as xr
import netCDF4 as nc
import matplotlib.pyplot as plt

path_to_nc="my/path/file.nc"

ds=xr.open_dataset(path_to_nc)
print(ds)
>>>

<xarray.Dataset>
Dimensions:  (LAT: 4550, LON: 9300)
Coordinates:
  * LON      (LON) float64 -138.0 -138.0 -138.0 -138.0 ... -45.03 -45.01 -45.01
  * LAT      (LAT) float64 68.0 67.99 67.97 67.96 ... 22.53 22.52 22.51 22.5
Data variables:
    PM25     (LAT, LON) float32 ...

文件确实有值(不仅仅是 nan)。

# Range of values:
ds=ds['PM25']
print(ds)
>>>

<xarray.DataArray 'PM25' (LAT: 4550, LON: 9300)>
array([[1.6, 1.6, 1.6, ..., 1.2, 1.2, 1.2],
       [1.6, 1.6, 1.6, ..., 1.2, 1.2, 1.2],
       [1.6, 1.6, 1.6, ..., 1.2, 1.2, 1.2],
       ...,
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan]], dtype=float32)
Coordinates:
  * LON      (LON) float64 -138.0 -138.0 -138.0 -138.0 ... -45.03 -45.01 -45.01
  * LAT      (LAT) float64 68.0 67.99 67.97 67.96 ... 22.53 22.52 22.51 22.5
Attributes:
    standard_name:  PM25
    units:          ug/m3

但如果我尝试绘制这些值,则会得到一个空斧头。

ds.plot()

Output

问题是您试图同时绘制太多数据。如果您只是 select 它们的一个子集,它就可以工作:

#select data
dssel=ds.where((-125 < ds.LON) & (ds.LON < -115)
         & (49 < ds.LAT) & (ds.LAT < 55), drop=True)
#plot PM2.5
plt.figure()
dssel.PM25.plot()

结果如下:

有趣的是,如果您直接使用 matplotlib 绘制数据,速度会快得多,而且我能够绘制整个数据集(在我 4 岁但不是特别快的笔记本电脑上大约需要 20 秒)。在这种情况下,我使用 netCDF4 库加载 PM2.5 数据集。

from netCDF4 import Dataset
nc_fid = Dataset(fpath, 'r')

lats = nc_fid.variables['LAT'][:]  # extract/copy the data
lons = nc_fid.variables['LON'][:]
PM25 = nc_fid.variables['PM25'][:]

fig, axs = plt.subplots(figsize=(15, 10), nrows=2,ncols=1,gridspec_kw={'height_ratios': [20,1.5]},constrained_layout=True)
pcm=axs[0].pcolormesh(lons,lats,PM25,cmap='viridis')
cbar=fig.colorbar(pcm,cax=axs[1], extend='both', orientation='horizontal')
cbar.set_label('PM 2.5 [$\mu$g m$^{-3}]$')

我发现最初的问题与作为默认绘图选项嵌入到 xarray 中的函数 pcolormesh() 有关 (ds.plot() == ds.plot.pcolormesh())。如果使用 ds.plot.imshow(),数字会更快更正确地出现,而不需要 select 数据的子集(更多信息在这里:http://xarray.pydata.org/en/stable/plotting.html