Matplotlib的底图似乎不存储地图的中心,以便以后过度绘制数据

问题描述 投票:0回答:3

我想将NOAA地球系统研究实验室物理科学部的平均日温度绘制到用matplotlibBasemap创建的地图上。

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

然而,我的问题是,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一切看起来都很好(它不是我想要的中心位置)

我觉得解决方案很明显,我很感激任何提示指向我的方向。

python matplotlib matplotlib-basemap
3个回答
2
投票

如评论所述,数据的范围是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]

完整代码:

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

# read netCDF4 dataset
tmprt_dSet = netCDF4.Dataset('data/air.sig995.2018.nc')

# 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()

###  Section added ################
# 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]

##################################


fig1, ax1 = plt.subplots(1,1, figsize=(8,6) )
# 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()

enter image description here


1
投票

这很有挑战性。我将数据阵列分成两部分。第一部分从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


1
投票

到目前为止发布的两个答案都是我的问题的解决方案(谢谢你,ImportanceOfBeingErnestswatchai)。

然而,我认为必须有一种更简单的方法来做到这一点(简单来说,我的意思是一些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

© www.soinside.com 2019 - 2024. All rights reserved.