Python使用Cartopy绘制地图时如何添加矩形框选定指定子区域
在Cartopy地图上添加指定经纬度范围矩形标记的实现方案
直接借助matplotlib.patches.Rectangle补丁即可实现,核心是要给矩形指定正确的坐标投影,避免位置偏移。
完整实现代码
import cartopy.crs as ccrs import matplotlib.pyplot as plt from matplotlib.patches import Rectangle ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([-80, 40, 20, 90], crs=ccrs.PlateCarree()) ax.coastlines(resolution='50m', linewidth=.5, color='black') # 绘制范围为 lon∈(-10,20)、lat∈(30,70) 的矩形框 region_rect = Rectangle( xy=(-10, 30), # 矩形左下角点的经纬度(最小经度、最小纬度) width=30, # 经度跨度:20 - (-10) = 30 height=40, # 纬度跨度:70 - 30 = 40 facecolor='none', # 内部无填充,不遮挡底图 edgecolor='red', # 边框设为红色,可按需调整颜色、线宽 linewidth=2, transform=ccrs.PlateCarree() # 声明矩形坐标使用等经纬度投影,和底图匹配 ) ax.add_patch(region_rect) plt.show()
注意事项
- 必须传入
transform=ccrs.PlateCarree()参数,否则矩形会按照画布的像素坐标定位,出现在错误位置 - 如果需要调整矩形样式,直接修改
edgecolor、linewidth、linestyle参数即可,比如要虚线边框就加linestyle='--' - 如果需要给矩形填充半透明颜色,可以把
facecolor设为对应颜色,再加alpha=0.3调整透明度
内容的提问来源于stack exchange,提问作者lola
相关产品推荐
相关产品推荐

