在 Cartopy 地图中,我希望没有被任何数据(在我的域之外)覆盖的区域以浅灰色显示。玩过background_patch
并查看了这个示例更改投影 Matplotlib 轴的背景颜色,但仍然无法弄清楚我想要做什么。
这是一个人为的例子,我用红线使域边界可见。相反,我希望将红线以外的区域涂成浅灰色。
非常感谢!
编辑: 将投影更改为 LambertConformal 以证明下面提出的解决方案(Cartopy 背景颜色(数据域外))仅适用于矩形网格。请参阅下面的附加图。
import matplotlib.pyplot as plt
import matplotlib as mpl
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import numpy as np
#create some lons/lats
lats = np.linspace(20,40,50)
lons = np.linspace(110,130,50)
lons,lats = np.meshgrid(lons,lats)
#some data
thedata = np.zeros_like(lats)
#some 'cloud' in the data
thedata[5:8,7:13] = 1
#theproj = ccrs.Mercator()
theproj = ccrs.LambertConformal() #choose another projection to obtain non-rectangular grid
ef, axar = plt.subplots(1,1, subplot_kw={'projection': theproj})#, 'axisbg': 'w'
ef.subplots_adjust(hspace=0.,wspace=0.,bottom=0.05,top=0.95,left=0.03,right=0.98)
axar.coastlines()
mycmap = mpl.colors.ListedColormap(['white', 'black'])
bounds=[0,0.5,1]
norm = mpl.colors.BoundaryNorm(bounds, mycmap.N)
im = axar.pcolormesh(lons,lats,thedata,cmap=mycmap, transform=ccrs.PlateCarree())
im.set_norm(norm)
#make the extent larger to see a margin outside of the domain
axar.set_extent([lons[0,0]-1,lons[-1,-1]+1,lats[0,0]-1,lats[-1,-1]+1])
#for illustration: make the domain bounds visible
#but instead of the red domain bounds I would like to have the background (outside of the domain) in some color (lightgrey)
axar.plot(lons[:,0],lats[:,0],'r', transform=ccrs.PlateCarree())
axar.plot(lons[:,-1],lats[:,0],'r', transform=ccrs.PlateCarree())
axar.plot(lons[0,:],lats[0,:],'r', transform=ccrs.PlateCarree())
axar.plot(lons[0,:],lats[-1,:],'r', transform=ccrs.PlateCarree())
#some decoration to see where we are
gl = axar.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
plt.show()