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關鍵字設置數據投影,請謹記:在任何情況下,請務必設置axes的projection參數與數據點的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