如何移除Cartopy/Matplotlib绘图的外边框并保留经纬度内边框
解决方案
你遇到的0-1范围多余外框是matplotlib默认边距和tight布局自动加边距导致的,按下面修改代码即可保留带经纬度的内边框、仅移除外部多余边框:
核心修改点:
- 创建画布时直接将子图边距设为0,让地图轴占满整张画布,避免默认留白
- 删掉
fig.bbox_inches='tight'配置,保存图片时指定pad_inches=0取消额外边距
修改后的完整代码参考:
df = days_dict[t] proj = ccrs.PlateCarree() # 新增:创建画布并设置边距为0 fig = plt.figure() fig.subplots_adjust(left=0, right=1, bottom=0, top=1) # 让轴占满整个画布 ax = fig.add_axes([0, 0, 1, 1], projection=proj) bounds = [-125.0011, -66.9326, 49.5904, 24.9493] ax.set_extent(bounds, crs=ccrs.PlateCarree()) im = ax.scatter(df['long'], df['lat'], c=df['mean_no2'], s=8, cmap=cm.bwr, vmin=0, vmax=40) cartography(ax) axins = inset_axes(ax, width="90%", height="10%", loc='lower center', borderpad=-3) cbar = plt.colorbar(im, label='NO2 concentration (ppb)', orientation='horizontal', cax=axins, fraction=0.046, norm=norm, anchor=(0.5, -1)) cbar.set_ticks(np.arange(0, 40, 10)) plt.show() axins.frameon = False out_name = out_folder + r'\frame%s.png' % t # 保存时去掉tight配置,加pad_inches=0取消边距 fig.savefig(out_name, bbox_inches=None, pad_inches=0) fig.clear()
补充说明:
不要修改ax的frameon属性,就能保留你需要的带经纬度的内边框。你之前设置的fig.frameon = False可以保留,也可以删掉,只要边距设为0就不会出现多余外框。
内容的提问来源于stack exchange,提问作者Xavier Nogueira
相关产品推荐
相关产品推荐

