Python Cartopy添加Shapefile后图例不显示问题求助
Cartopy Shapefile图例不显示的解决方法
你遇到的问题根源在于ax.add_geometries()方法不会将要素的label参数关联到matplotlib的图例系统,导致调用ax.legend()时找不到带标签的绘图元素,最终出现空白图例和报错。
以下是两种可行的解决方法:
方案一:使用ax.add_feature()(推荐)
Cartopy的add_feature()方法是专门为添加地理要素设计的,会自动处理图例标签的关联,代码更简洁:
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) # 定义并添加陆地要素 land_feature = cfeature.NaturalEarthFeature( 'physical', 'land', '50m', edgecolor='black', facecolor='gray', label='Land' ) ax.add_feature(land_feature) # 定义并添加海洋要素 ocean_feature = cfeature.NaturalEarthFeature( 'physical', 'ocean', '50m', edgecolor='face', facecolor='blue', label='Ocean' ) ax.add_feature(ocean_feature) ax.set_title('Map with Shapefile Legend') ax.gridlines() ax.legend(loc='lower left') plt.show()
方案二:手动创建图例条目
如果必须使用ax.add_geometries(),可以通过matplotlib的Patch对象手动构建图例元素:
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from matplotlib.patches import Patch fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) # 添加陆地和海洋几何要素 ax.add_geometries( cfeature.NaturalEarthFeature('physical', 'land', '50m').geometries(), ccrs.PlateCarree(), facecolor='gray', edgecolor='black' ) ax.add_geometries( cfeature.NaturalEarthFeature('physical', 'ocean', '50m').geometries(), ccrs.PlateCarree(), facecolor='blue', edgecolor='face' ) # 手动创建图例补丁 legend_patches = [ Patch(facecolor='gray', edgecolor='black', label='Land'), Patch(facecolor='blue', edgecolor='face', label='Ocean') ] ax.set_title('Map with Shapefile Legend') ax.gridlines() # 传入手动创建的补丁生成图例 ax.legend(handles=legend_patches, loc='lower left') plt.show()
内容的提问来源于stack exchange,提问作者Rony Golder
相关产品推荐
相关产品推荐

