You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重叠绘制多张地图时如何减小两个垂直图例的水平间距

解决方法

你遇到的问题是因为legend_kwds中的pad参数仅控制单图例和主绘图区域的间距,无法调整多个图例之间的间距,直接操作colorbar对应的轴对象即可解决,提供两种可行方案:

方案1:事后调整已有图例位置

在你原有代码的基础上,添加以下代码调整两个colorbar的间距即可:

# 获取画布对象
fig = base1.figure
# 画布共3个axes:第0位是主地图轴,后两位分别是两个垂直图例的colorbar轴
ax_main, cbar_crk, cbar_pk = fig.axes

# 读取第一个图例的位置参数 [左边界, 下边界, 宽度, 高度]
pos_crk = cbar_crk.get_position()
# 修改第二个图例的左边界,向左移动缩小间距,可根据需求调整0.02的数值
cbar_pk.set_position([pos_crk.x0 + 0.02, pos_crk.y0, pos_crk.width, pos_crk.height])

# 保存时加bbox_inches='tight'避免边缘被截断
plt.savefig('rep_heatmap.jpg', dpi=300, bbox_inches='tight')

方案2:预先自定义图例位置(更可控)

绘图前提前创建好两个挨近的colorbar轴,绘图时直接指定,避免自动布局产生的多余间距:

import matplotlib.pyplot as plt

# 提前创建主画布和主绘图轴
fig, ax = plt.subplots(1, 1, figsize=(18, 16))
# 自定义两个colorbar的位置,参数为[左边界, 下边界, 宽度, 高度],可自行调整数值控制间距
cbar_crk = fig.add_axes([0.86, 0.3, 0.02, 0.4])
cbar_pk = fig.add_axes([0.91, 0.3, 0.02, 0.4])

# 绘制第一张图,指定对应colorbar轴
base1 = rep_crk.plot(
    ax=ax, column='pct_rep_crk', cmap='Oranges', legend=True, 
    vmin=0, vmax=1, hatch='.', aspect=1,
    legend_kwds={'label':'Percent Rep Cracked', 'orientation':'vertical', 'cax': cbar_crk}
)
# 绘制第二张图,指定对应colorbar轴
base2 = rep_pk.plot(
    ax=base1, column='pct_rep_pk', cmap='Purples', legend=True, vmin=0, vmax=1,
    legend_kwds={'label':'Percent Rep Packed', 'orientation':'vertical', 'cax': cbar_pk}
)
# 绘制行政区边界
districts.plot(ax=base2, edgecolor='black', linewidth=1, facecolor='none')

plt.title('Percent of Republicans Packed and Cracked Relative to 1055 Comparators')
plt.axis('off')
plt.savefig('rep_heatmap.jpg', dpi=300, bbox_inches='tight')

内容的提问来源于stack exchange,提问作者Jerry Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:24:04