在Python Cartopy绘图中添加二维直方图导致范围重置
问题解决:Cartopy中使用hist2d后地图范围缩小
问题原因
ax.hist2d()会自动调整坐标轴范围以适配所有直方图数据,这会覆盖你之前通过ax.set_extent()设置的地图范围,导致地图被“压缩”到仅显示直方图数据的边界。
代码修正步骤
- 修复未定义变量:代码中
ax2是未声明的变量,需替换为当前创建的轴对象ax。 - 锁定地图范围:要么在绘制直方图后重新调用
ax.set_extent(extent)强制恢复范围,要么在hist2d中指定range参数限制直方图的坐标区间,避免轴范围被自动修改。
修正后的完整代码
import cartopy.crs as ccrs import cartopy.feature as cfeat import matplotlib.pyplot as plt # 补充特征定义(假设原代码中已存在) USCOUNTIES = cfeat.NaturalEarthFeature( category='cultural', name='admin_2_counties', scale='5m', facecolor='none' ) state_borders = cfeat.NaturalEarthFeature( category='cultural', name="admin_1_states_provinces_lakes", scale='10m', facecolor='none' ) proj = ccrs.LambertConformal() fig, ax = plt.subplots(figsize=(10,10), subplot_kw=dict(projection=proj)) extent = ([-99,-92, 27, 31.3]) # 修正ax2为ax,转换坐标 xynps = ax.projection.transform_points(ccrs.PlateCarree(), lon_array, lat_array) ax.set_extent(extent) ax.add_feature(USCOUNTIES.with_scale('5m'), edgecolor="gray") ax.add_feature(state_borders, linestyle='solid', edgecolor='black') ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False) # 添加散点图 ax.scatter(-95.36, 29.76, transform=ccrs.PlateCarree(), marker='*', s=400, color="orange") # Houston ax.scatter(lon_small, lat_small, transform=ccrs.PlateCarree(), marker='.', s=0.001, c="red") # 方法1:绘制直方图后重置范围 h = ax.hist2d(xynps[:,0], xynps[:,1], bins=100, zorder=10, alpha=0.75, cmin=120) ax.set_extent(extent) # 强制恢复地图范围 # 方法2:提前转换地理范围为投影坐标,指定hist2d的range参数 # x0, y0 = proj.transform_point(extent[0], extent[2], ccrs.PlateCarree()) # x1, y1 = proj.transform_point(extent[1], extent[3], ccrs.PlateCarree()) # h = ax.hist2d(xynps[:,0], xynps[:,1], bins=100, zorder=10, alpha=0.75, cmin=120, range=[[x0, x1], [y0, y1]]) plt.show()
关键说明
- 方法1操作简单,通过重置extent覆盖hist2d自动调整的范围,适合快速修复问题。
- 方法2更严谨,通过限制直方图的坐标区间,既避免轴范围被修改,又确保直方图仅绘制在指定的地图区域内。
内容的提问来源于stack exchange,提问作者Philip Espinal
相关产品推荐
相关产品推荐

