Lambert投影WRF数据绘图问题:海岸线无法正确叠加显示
关于WRF输出数据绘图与文件读取的问题
一、绘图时海岸线异常问题
近期在Windows系统的Jupyter中使用Python绘制netCDF数据,处理采用Lambert Conformal投影的WRF输出数据时,出现海岸线完全不显示或与数据图偏移的情况,怀疑是数据的Lambert投影导致该问题。
代码运行输出:
二、Dataset读取WRF文件报错
尝试用Dataset打开WRF输出文件(如ncfile = Dataset("wrfout_d01_2016-10-07_00_00_00"))时,出现以下错误:
61 lons = wrfnc.variables[lonvar][:] 663 # Need to check all times --> 664 for i in py3range(lats.shape[-3]): 665 start_idxs = [0] * len(lats.shape) # PyNIO does not support ndim 666 start_idxs[-3] = i IndexError: tuple index out of range
三、尝试使用的代码
from netCDF4 import Dataset import xarray as xr import matplotlib.pyplot as plt import cartopy.crs as ccrs ds = xr.open_dataset("output_mean.nc") temp2 = ds.T2[0,:,:] temp2 fig = plt.figure(figsize=(5, 5)) ax1 = plt.axes(projection=ccrs.LambertConformal()) ax1.coastlines() temp2.plot(ax=ax1, cmap='jet', transform=ccrs.LambertConformal()) ax1.set_extent([-140, -75, 17, 45], crs=ccrs.PlateCarree()) ax1.coastlines() plt.show()
解决方案
1. 解决海岸线显示异常问题
你的判断正确,投影参数不匹配是核心原因。Cartopy默认的LambertConformal()参数和WRF输出的自定义Lambert投影参数(标准纬线、中心经纬度等)不一致,导致数据与海岸线坐标系错位。
处理步骤:
- 从WRF数据集中提取投影参数:
# 从xarray数据集获取WRF专属投影参数 wrf_proj = ccrs.LambertConformal( central_longitude=ds.STAND_LON, central_latitude=ds.MOAD_CEN_LAT, standard_parallels=(ds.TRUELAT1, ds.TRUELAT2), globe=ccrs.Globe(semimajor_axis=6370000, semiminor_axis=6370000) ) - 修改绘图代码,使用自定义投影匹配数据:
fig = plt.figure(figsize=(8, 6)) ax1 = plt.axes(projection=wrf_proj) ax1.coastlines(resolution='50m') # 指定分辨率提升海岸线清晰度 # 绘图时transform必须设置为WRF的自定义投影 temp2.plot(ax=ax1, cmap='jet', transform=wrf_proj) # 用数据自身的经纬度范围设置显示区域(避免手动范围的投影转换误差) lons = ds.XLONG[0, :, :] lats = ds.XLAT[0, :, :] ax1.set_extent([lons.min(), lons.max(), lats.min(), lats.max()], crs=wrf_proj) plt.show()
2. 解决Dataset读取文件的IndexError
WRF输出文件的维度结构特殊,netCDF4.Dataset原生读取容易出现维度索引错误,推荐两种更可靠的方式:
- 继续使用你已经在尝试的xarray:
xr.open_dataset("wrfout_d01_2016-10-07_00_00_00"),xarray能自动适配WRF的维度结构。 - 使用专门处理WRF数据的
wrf-python库:- 安装库:
pip install wrf-python - 读取文件并提取变量:
from wrf import open_wrf, getvar wrf_ds = open_wrf("wrfout_d01_2016-10-07_00_00_00") temp2 = getvar(wrf_ds, "T2") # 直接提取2米温度变量
- 安装库:
wrf-python会自动处理WRF的投影、维度等细节,避免手动处理的错误。
内容的提问来源于stack exchange,提问作者Jean
相关产品推荐
相关产品推荐

