我想把NOAA地球系统研究实验室物理科学部的日均温度绘制在一张用matplotlib
Basemap
绘制的地图上。在
数据集可以作为netCDF文件从here下载。在
但是,我的问题是Basemap
似乎没有存储地图的中心(或边界框)坐标,因为后续的超绘只填充了地图的一部分,请参见下图:
生成图形的代码如下:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import netCDF4
# to check whether a file exists (before downloading it)
import os.path
import sys
fig1, ax1 = plt.subplots(1,1, figsize=(8,6) )
temperature_fname = 'air.sig995.2016.nc'
url = 'https://www.esrl.noaa.gov/psd/thredds/fileServer/Datasets/ncep.reanalysis.dailyavgs/surface/{0}'.format( temperature_fname)
if not os.path.isfile( temperature_fname ):
print( "ERROR: you need to download the file {0}".format(url) )
sys.exit(1)
# read netCDF4 dataset
tmprt_dSet = netCDF4.Dataset( temperature_fname )
# extract (copy) the relevant data
tmprt_vals = tmprt_dSet.variables['air'][:] - 273.15
tmprt_lat = tmprt_dSet.variables['lat'][:]
tmprt_lon = tmprt_dSet.variables['lon'][:]
# close dataset
tmprt_dSet.close()
# use the Miller projection
map1 = Basemap( projection='mill', resolution='l',
lon_0=0., lat_0=0.
)
# draw coastline, map-boundary
map1.drawcoastlines()
map1.drawmapboundary( fill_color='white' )
# draw grid
map1.drawparallels( np.arange(-90.,90.,30.), labels=[1,0,0,0] )
map1.drawmeridians( np.arange(-180.,180.,60.),labels=[0,0,0,1] )
# overplot temperature
## make the longitude and latitude grid projected onto map
tmprt_x, tmprt_y = map1(*np.meshgrid(tmprt_lon,tmprt_lat))
## make the contour plot
CS1 = map1.contourf( tmprt_x, tmprt_y, tmprt_vals[0,:,:],
cmap=plt.cm.jet
)
cbar1 = map1.colorbar( CS1, location='right' )
cbar1.set_label( r'$T$ in $^\circ$C')
plt.show()
注意:如果我设置lon_0=180
一切看起来都很好(只是不是我想要的中间位置)
我有一种感觉,解决方案是非常明显的,我会很感激任何提示我朝这个方向。在
这很有挑战性。我把数据数组分成两部分。第一部分跨越经度0°到180°E。位于0°西侧的第二部分需要360°的经度偏移。Colormap必须规范化并应用以获取公共参考颜色。以下是工作代码和结果图:
结果图:
如前所述,数据的范围是从0到360,而不是-180到180。所以你需要
在数据提取和绘图函数之间添加以下代码可以做到这一点。在
完整代码:
^{pr2}$到目前为止发布的两个答案都是我问题的答案(谢谢,ImportanceOfBeingErnest和{a2})。在
然而,我认为必须有一种更简单的方法来实现这一点(我所说的simple是指某种
Basemap
实用程序)。所以我再次查看了文档[1],发现了一些我至今忽略的东西:mpl_toolkits.basemap.shiftgrid
。代码中需要添加以下两行:注意,第二行必须在
meshgrid
调用之前添加。在[1]https://matplotlib.org/basemap/api/basemap_api.html
相关问题 更多 >
编程相关推荐