Skip to main content
 首页 » 编程设计

python之Cartopy 投影随着不同的数据/意外行为而变化

2024年09月07日7Free-Thinker

我正在从 basemap 迁移到 cartopy,所以我仍在努力寻找线索!如果我在投影上绘制一些数据,我希望它绘制 map 然后在顶部绘制数据,就像这样

import cartopy.crs as ccrs 
import matplotlib.pyplot as plt 
import numpy as np 
 
latitude = np.linspace(-90, 90, 180) 
longitude = np.linspace(-180,180,360) 
data = np.cos(np.deg2rad(latitude[:, np.newaxis])) + np.sin(np.deg2rad(longitude)) 
crs = ccrs.Orthographic(-30,45) #some sample data 
 
ax1 = plt.subplot(121,projection=crs) 
ax1.contourf(longitude, latitude,data, transform=ccrs.PlateCarree()) 
ax1.coastlines('110m', edgecolor='black', linewidth=0.75) 

这将使用数据生成真实的地形投影。但是,如果我将某些数据设置为 void/nan,它就不再在同一个域上绘制:

data[0:150,:] = np.nan 
 
ax1 = plt.subplot(122,projection=crs) 
ax1.contourf(longitude, latitude,data, transform=ccrs.PlateCarree()) 
ax1.coastlines('110m', edgecolor='black', linewidth=0.75) 
 
plt.show() 

从 basemap 中,我希望绘制相同的域,但数据是 nan 的地方它只会是白色的。我如何强制 cartopy 停止“自动调整”数据,并保持相同的投影?

data[0:150,:] = np.nan 如何影响下方投影的图片。 提前致谢!我尝试用 ax1.set_extent([-180, 180, -90, 90], ccrs.PlateCarree()) 强制执行它,但无济于事。

请您参考如下方法:

Cartopy 始终尝试使域适合数据范围。如果您想查看全局绘图,请使用 ax1.set_global() 强制执行此操作:

import cartopy.crs as ccrs 
import matplotlib.pyplot as plt 
import numpy as np 
 
latitude = np.linspace(-90, 90, 180) 
longitude = np.linspace(-180,180,360) 
data = np.cos(np.deg2rad(latitude[:, np.newaxis])) + np.sin(np.deg2rad(longitude)) 
crs = ccrs.Orthographic(-30,45) #some sample data 
 
ax1 = plt.subplot(121,projection=crs) 
ax1.contourf(longitude, latitude,data, transform=ccrs.PlateCarree()) 
ax1.coastlines('110m', edgecolor='black', linewidth=0.75) 
 
data[0:150,:] = np.nan 
 
ax1 = plt.subplot(122,projection=crs) 
ax1.contourf(longitude, latitude,data, transform=ccrs.PlateCarree()) 
ax1.coastlines('110m', edgecolor='black', linewidth=0.75) 
ax1.set_global() 
 
plt.show()