Matplotlib绘图中如何使cbar_bottom与ax2视觉宽度一致?
解决Matplotlib子图布局中底部色条与关联矩阵宽度不匹配的问题
问题根源在于你对subgridspec的单元格索引错误,底部色条没有放在关联矩阵的正下方,导致宽度比例不匹配。以下是修正后的实现方案:
修正后的代码
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.colors import ListedColormap import numpy as np np.random.seed(123941) data = np.random.rand(20, 20) cmap_bm_type = ListedColormap(['mediumseagreen', 'greenyellow', 'darkorchid', 'plum']) fig = plt.figure(figsize=[12, 8]) # 主布局:2行2列,调整左右宽度比例让布局更协调 gs = gridspec.GridSpec(2, 2, figure=fig, width_ratios=[0.4, 0.6]) # 左侧两个常规子图 ax1 = fig.add_subplot(gs[0, 0]) ax1.set_title("左侧子图1") ax3 = fig.add_subplot(gs[1, 0]) ax3.set_title("左侧子图2") # 右上角区域的子布局:2行3列 # 行比例:第一行(关联矩阵+左右色条)占90%高度,第二行(底部色条)占10% # 列比例:左右色条各占10%宽度,中间关联矩阵占80% sgs = gs[0, 1].subgridspec(2, 3, height_ratios=[0.9, 0.1], width_ratios=[0.1, 0.8, 0.1], wspace=0.02, hspace=0.02) # 减小间距,让元素更贴合 # 关联矩阵(中间单元格) ax2 = fig.add_subplot(sgs[0, 1]) im = ax2.imshow(data, cmap=cmap_bm_type) ax2.axis('off') ax2.set_title("关联矩阵") # 左侧垂直色条(第一行第一列) cbar_left = fig.add_subplot(sgs[0, 0]) fig.colorbar(im, cax=cbar_left, orientation='vertical') cbar_left.tick_params(labelsize=8) # 底部水平色条(第二行第二列,与关联矩阵同列) cbar_bottom = fig.add_subplot(sgs[1, 1]) fig.colorbar(im, cax=cbar_bottom, orientation='horizontal') cbar_bottom.tick_params(labelsize=8) # 右侧垂直色条(第一行第三列) cbar_right = fig.add_subplot(sgs[0, 2]) fig.colorbar(im, cax=cbar_right, orientation='vertical') cbar_right.tick_params(labelsize=8) plt.tight_layout() plt.show()
关键调整说明
- 单元格索引修正:将底部色条放在
sgs[1,1](第二行第二列),与关联矩阵sgs[0,1]处于同一列,确保宽度比例完全匹配 - 布局比例优化:通过
height_ratios和width_ratios明确划分各区域的占比,保证色条与关联矩阵的尺寸对应 - 色条绑定:使用
fig.colorbar将色条轴与关联矩阵的图像对象绑定,实现正确的颜色映射 - 间距调整:减小
wspace和hspace的值,让色条与关联矩阵的视觉衔接更自然
内容的提问来源于stack exchange,提问作者Jaka Kovše
相关产品推荐
相关产品推荐

