netCDF4-Python绘图变量

时间:2017-11-16 16:18:52

标签: python plot netcdf

enter image description here我想使用netCDF4-Python从netCDF文件中绘制一系列变量。我使用以下代码:

import numpy as np
import pandas as pd
from pylab import *
from netCDF4 import Dataset
pals = Dataset('pals_amplero_2003_2006_ecmwf_v1.nc4', "a",format='NETCDF4')
print (pals.variables.keys())
print (pals.variables['Rainf'])
print (pals.variables['Evap'])
print (pals.variables['time'])
evap = pals.variables['Evap'][:,:]
rain = pals.variables['Rainf'][:,:]
subplot(2,1,1)
pcolor(evap)
subplot(2,1,2)
pcolor(rain)

不幸的是,它输出了一条错误消息(在随附文档中有更详细的内容):

ValueError: too many values to unpack (expected 2)

有关信息,以下是打印命令的输出

odict_keys(['DelIntercept', 'DelSWE', 'DelSoilMoist', 'Evap', 'Qs', 'Qsb',      'Qsm', 'Rainf', 'Snowf', 'lat', 'lon', 'nlevs', 'time', 'timestp', 'M_fieldcap', 'M_sat', 'M_wilt', 'SoilDepth', 'CanopInt', 'Conds', 'ECanop', 'ESoil', 'RootMoist', 'SubSnow', 'TVeg', 'DelColdCont', 'DelSoilHeat', 'LWnet', 'LWup', 'Qf', 'Qg', 'Qh', 'Qle', 'SWnet', 'Fdepth', 'HFLUXRF', 'IceFrac', 'MFLUXRF', 'SAlbedo', 'SnowDepth', 'SnowFrac', 'Tdepth', 'WSN', 'AvgSurfT', 'HLICE', 'HLML', 'SWE', 'SnowT', 'SoilMoist', 'SoilTemp', 'TLBOT', 'TLICE', 'TLMNW', 'TLSF', 'TLWML', 'icetemp', 'snowdens', 'Albedo', 'BaresoilT', 'RH2m', 'RadT', 'T2m', 'VegT', 'Bgain', 'Biomstr', 'Biomstr2', 'Bloss', 'biomass', 'lai', 'Ag', 'An', 'CO2flux', 'Rd', 'Reco', 'Rsoil_str'])
<class 'netCDF4._netCDF4.Variable'>
float32 Rainf(time, y, x)
units: mm/day
long_name: Rainfall rate
associate: time y x
missing_value: 1e+20
time_representation: average over past model timestep
unlimited dimensions: time
current shape = (70084, 1, 1)
filling on, default _FillValue of 9.969209968386869e+36 used

<class 'netCDF4._netCDF4.Variable'>
float32 Evap(time, y, x)
units: mm/day
long_name: Total evapotranspiration
associate: time y x
missing_value: 1e+20
time_representation: average over past model timestep
unlimited dimensions: time
current shape = (70084, 1, 1)
filling on, default _FillValue of 9.969209968386869e+36 used

<class 'netCDF4._netCDF4.Variable'>
float64 time(time)
units: seconds since 2003-01-01 00:00:00
long_name: Time in seconds
Time_label: Start of output interval
unlimited dimensions: time
current shape = (70084,)
filling on, default _FillValue of 9.969209968386869e+36 used

1 个答案:

答案 0 :(得分:1)

最后看到问题。以此示例(随机NetCDF文件):

ncdump -h th.xz.nc

给予(除其他事项外):

float th(time, z, x, y) ;

因此变量th有4个维度。如果您以与代码中类似的方式阅读/绘制此内容:

import netCDF4 as nc4
import matplotlib.pylab as pl

nc = nc4.Dataset('th.xz.nc')
th = nc.variables['th'][:,:]

pl.figure()
pl.pcolor(th)

它给出了同样的错误:

  

ValueError:解压缩的值太多(预期2)

为什么呢?使用[:,:](或[:][:,:,:])切片仍会为您提供两个以上的维度:

print(th.shape)
  

(9,32,32,1)

pcolor期望二维数组。解决方案很简单;您需要选择要显示的2D切片,例如pcolor(evap[0,:,:])x-y切片)或pcolor(evap[:,0,:])time-x切片),或者......