(三)理解Cartopy中投影关键字

1、使用默认的投影

  首先使用numpy创建一些需要绘制的数据点(共25*25个),代码如下:

import numpy as np


lon = np.linspace(-80, 80, 25)
lat = np.linspace(30, 70, 25)
lon2d, lat2d = np.meshgrid(lon, lat)

data = np.cos(np.deg2rad(lat2d) * 4) + np.sin(np.deg2rad(lon2d) * 4)
print(data.shape)

   不设置数据投影类型,绘制这些数据点,代码如下:

# The projection keyword determines how the plot will look
plt.figure(figsize=(6, 3))
ax = plt.axes(projection=ccrs.PlateCarree()) # axes的projection参数最好设置,此处选择PlateCarree()
ax.set_global() 
ax.coastlines()
ax.contourf(lon, lat, data)
# 此处不设置数据点投影类型
plt.show()

 

  从绘制结果可以看出,结果是正确的,实质为默认数据投影与PlateCarree()保持一致。下面设置数据投影类型,代码如下:

data_crs = ccrs.PlateCarree()

# The projection keyword determines how the plot will look
plt.figure(figsize=(6, 3))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines()

ax.contourf(lon, lat, data, transform=data_crs)
plt.show()

  使用transform关键字设置数据投影,请谨记:在任何情况下,请务必设置axesprojection参数与数据点的transform参数。

2、axes投影与数据点不一致

  当改变axes的投影时,数据的transform必须与数据本身的投影保持一致,这样绘制的图才是正确的,代码如下:

data_crs = ccrs.PlateCarree()
# Now we plot a rotated pole projection
projection = ccrs.RotatedPole(pole_longitude=-177.5, pole_latitude=37.5)
plt.figure(figsize=(6, 3))
ax = plt.axes(projection=projection)
ax.set_global()
ax.coastlines()

ax.contourf(lon, lat, data,transform=data_crs)  #此处必须和数据本身投影保持一致
plt.show()

 

  可以看到,数据会“自动按照”axes的投影,进行转换,已被正确绘制在地图上。

 

 

3、更多示例

  下面进行更多示例进行佐证,代码如下:

data_crs = ccrs.PlateCarree()
# We can choose any projection we like...
projection = ccrs.InterruptedGoodeHomolosine()
plt.figure(figsize=(6, 7))
ax1 = plt.subplot(211, projection=projection)
ax1.set_global()
ax1.coastlines()
ax1.contourf(lon, lat, data, transform=data_crs)


ax2 = plt.subplot(212, projection=ccrs.NorthPolarStereo())
ax2.set_extent([-180, 180, 20, 90], crs=ccrs.PlateCarree())
ax2.coastlines()
ax2.contourf(lon, lat, data, transform=data_crs)
plt.show()

 

  可以看出,只要transform关键字设置正确,数据就可以在任意投影下显示正确。如果要设置数据显示范围,set_extent同样需要正确设置投影参数crs。

 

参考

Cartopy官网地址:https://scitools.org.uk/cartopy/docs/latest/tutorials/understanding_transform.html

 

posted @ 2021-01-20 15:15  气象学人  阅读(2349)  评论(0编辑  收藏  举报