1. 程式人生 > 實用技巧 >(三)理解Cartopy中投影關鍵字

(三)理解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