Matplotlib的基本地图似乎没有存储地图的中心,以便以后对d进行超绘

2024-10-02 10:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把NOAA地球系统研究实验室物理科学部的日均温度绘制在一张用matplotlibBasemap绘制的地图上。在

数据集可以作为netCDF文件从here下载。在

但是,我的问题是Basemap似乎没有存储地图的中心(或边界框)坐标,因为后续的超绘只填充了地图的一部分,请参见下图:

Map

生成图形的代码如下:

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一切看起来都很好(只是不是我想要的中间位置)

我有一种感觉,解决方案是非常明显的,我会很感激任何提示我朝这个方向。在


Tags: theimportnp地图pltvariablesfnamenetcdf4
3条回答

这很有挑战性。我把数据数组分成两部分。第一部分跨越经度0°到180°E。位于0°西侧的第二部分需要360°的经度偏移。Colormap必须规范化并应用以获取公共参考颜色。以下是工作代码和结果图:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import netCDF4
import matplotlib as mpl

#import os.path
#import sys

fig1, ax1 = plt.subplots(1,1, figsize=(10,6) )

temperature_fname =  r'.\air.sig995.2018.nc'

# read netCDF4 dataset
tmprt_dSet = netCDF4.Dataset( temperature_fname )

# extract (copy) the relevant data
shift_val = - 273.15
tmprt_vals = tmprt_dSet.variables['air'][:] + shift_val

tmprt_lat  = tmprt_dSet.variables['lat'][:]
tmprt_lon  = tmprt_dSet.variables['lon'][:]

# prep norm of the color map
color_shf = 40   # to get better lower range of colormap
normalize = mpl.colors.Normalize(tmprt_vals.data.min()+color_shf, \
                                 tmprt_vals.data.max())

# close dataset
#tmprt_dSet.close()

# use the Miller projection
map1 = Basemap( projection='mill', resolution='i', \
                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
# split data into 2 parts at column 73 (longitude: +180)
# part1 (take location as is)
beg_col = 0
end_col = 73
grdx, grdy = np.meshgrid(tmprt_lon[beg_col:end_col], tmprt_lat[:])
tmprt_x, tmprt_y = map1(grdx, grdy)
CS1 = map1.contourf( tmprt_x, tmprt_y, tmprt_vals[0,:, beg_col:end_col], 
                     cmap=plt.cm.jet, norm=normalize)

# part2 (longitude is shifted -360 degrees, but -359.5 looks better)
beg_col4 = 73
end_col4 = 144
grdx, grdy = np.meshgrid(tmprt_lon[beg_col4:end_col4]-359.5, tmprt_lat[:])
tmprt_x, tmprt_y = map1(grdx, grdy)
CS4 = map1.contourf( tmprt_x, tmprt_y, tmprt_vals[0,:, beg_col4:end_col4], 
                     cmap=plt.cm.jet, norm=normalize)

# color bars CS1, CS4 are the same (normalized), plot one only
cbar1 = map1.colorbar( CS1, location='right' )
cbar1.set_label( r'$T$ in $^\circ$C')

plt.show()

结果图:

enter image description here

如前所述,数据的范围是从0到360,而不是-180到180。所以你需要

  • 将范围从180到360度映射到-180到0。在
  • 将数据的后半部分移到前半部分之前,使其按升序排序。在

在数据提取和绘图函数之间添加以下代码可以做到这一点。在

# map lon values to -180..180 range
f = lambda x: ((x+180) % 360) - 180
tmprt_lon = f(tmprt_lon)
# rearange data
ind = np.argsort(tmprt_lon)
tmprt_lon = tmprt_lon[ind]
tmprt_vals = tmprt_vals[:, :, ind]

完整代码:

^{pr2}$

enter image description here

到目前为止发布的两个答案都是我问题的答案(谢谢,ImportanceOfBeingErnest和{a2})。在

然而,我认为必须有一种更简单的方法来实现这一点(我所说的simple是指某种Basemap实用程序)。所以我再次查看了文档[1],发现了一些我至今忽略的东西:mpl_toolkits.basemap.shiftgrid。代码中需要添加以下两行:

from mpl_toolkits.basemap import shiftgrid
tmprt_vals, tmprt_lon = shiftgrid(180., tmprt_vals, tmprt_lon, start=False)

注意,第二行必须在meshgrid调用之前添加。在


[1]https://matplotlib.org/basemap/api/basemap_api.html

相关问题 更多 >

    热门问题