matplotlib绘制netCDF数据的异常图表

1 投票
2 回答
1109 浏览
提问于 2025-04-18 10:45

我花了很长时间在找这个问题,所以任何帮助或提示我都会非常感激。

我想在南极海上绘制一些海冰浮板的数据(netCDF格式,网格化的总浮板),但是本来应该在南极周围好好显示的数据却出现在了我图像的底部。对我来说,netCDF和matplotlib都是比较新的东西,所以可能是我在处理维度或者投影的时候出了问题。

from scipy.io.netcdf import netcdf_file as Dataset
import numpy as np
import matplotlib.pyplot as plt

FB = Dataset('./datasets/fb-0217-0320.nc', 'r')
f = FB.variables['f'][:,:]
lat = FB.variables['lat'][:,0]
lon = FB.variables['lon'][0,:]
masked_fb = np.ma.masked_where(np.isnan(f), f)
mtx_lon, mtx_lat = np.meshgrid(lon, lat)
m = Basemap(projection='spstere',boundinglat=-50, lon_0=180., resolution='l')
m.bluemarble()

plt.figure()
m.pcolormesh(mtx_lon, mtx_lat, masked_fb, latlon=True)
plt.show()

使用ncdump命令得到的结果是:

dimensions:
x = 79 ;
y = 83 ;
variables:
float lat(y, x) ;
    lat:standard_name = "latitude" ;
    lat:long_name = "latitude coordinate" ;
    lat:units = "degrees_north" ;
float lon(y, x) ;
    lon:standard_name = "longitude" ;
    lon:long_name = "longitude coordinate" ;
    lon:units = "degrees_east" ;
float f(y, x) ;
    f:long_name = "total_freeboard" ;
    f:units = "mm" ;
    f:coordinates = "lat lon" ;

我注意到一个奇怪的事情,就是最小纬度是-5156.6201,但我不知道怎么计算有多少个这样的值……

编辑:按照Neil的建议,把代码格式化成常见的样式。

2 个回答

0

首先,通常我们会这样导入netcdf模块:

from scipy.io.netcdf import netcdf_file as Dataset

然后你可以读取文件并访问变量,方法是:

FB = Dataset('./datasets/fb-0217-0320.nc', 'r')
f = FB.variables['f'][:,:]
lat = FB.variables['lat'][:,:]
lon = FB.variables['lon'][:,:]

你确定 lat[:,0]lon[0,:] 读取网格坐标是正确的吗?ncdump显示它们是二维变量,我怀疑问题出在从 lat[:,0]lon[0,:] 创建 meshgrid 的过程中。

1

好的,我从matplotlib得到了帮助,觉得应该在这里分享一下,以防其他人也遇到类似的问题。问题出在meshgrid上。因为netCDF文件中的纬度和经度已经是二维的,所以其实不需要使用meshgrid。对我有效的解决方案是:

from scipy.io.netcdf import netcdf_file as Dataset
import numpy as np
import matplotlib.pyplot as plt

FB = Dataset('./datasets/fb-0217-0320.nc', 'r')
f = FB.variables['f'][:,:]
lat = FB.variables['lat'][:,:]
lon = FB.variables['lon'][:,:]
masked_fb = np.ma.masked_where(np.isnan(f), f)
m = Basemap(projection='spstere',boundinglat=-50, lon_0=180., resolution='l')
m.bluemarble()

plt.figure()
m.pcolormesh(lon, lat, masked_fb, latlon=True)
plt.show()

撰写回答