Python Matplotlib:如何拼接主图与侧边、顶边子图并添加独立色条?
解决方案:用GridSpec精准控制布局
其实不用换工具!axes_grid1虽然能实现,但用matplotlib.gridspec.GridSpec会更直观地控制各个子图和色条的位置比例,轻松搞定你要的贴合效果。下面是调整后的代码,完美匹配你想要的布局:
import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec # 生成数据 n = 20 Main = np.random.randn(n, n) Left = np.random.randn(n, 1) # 高度和Main匹配(n行) Top = np.random.randn(2, n) # 宽度和Main匹配(n列),这里调整了shape避免转置,如果你习惯原来的(n,2),加个.T就行 # 创建整体画布和GridSpec布局 fig = plt.figure(figsize=(8, 8)) # 定义网格:行分为3部分(Top色条、Top图、Main图),列分为4部分(Left色条、Left图、Main图、Main色条) # 比例可以按需调整,色条占比小一点更美观 gs = GridSpec( nrows=3, ncols=4, height_ratios=[0.1, 0.2, 1], # 行比例:Top色条 < Top图 < Main图 width_ratios=[0.1, 0.2, 1, 0.1], # 列比例:Left色条 < Left图 < Main图 < Main色条 wspace=0.05, hspace=0.05 # 子图间距设极小,实现贴合效果 ) # 分配各个坐标轴位置 ax_main = fig.add_subplot(gs[2, 2]) # Main图:第3行(索引2)、第3列(索引2) ax_top = fig.add_subplot(gs[1, 2]) # Top图:第2行(索引1)、第3列(索引2) ax_left = fig.add_subplot(gs[2, 1]) # Left图:第3行(索引2)、第2列(索引1) # 分配各个色条的坐标轴 ax_main_cbar = fig.add_subplot(gs[2, 3]) ax_top_cbar = fig.add_subplot(gs[0, 2]) ax_left_cbar = fig.add_subplot(gs[2, 0]) # 绘制Main图和对应色条 im_main = ax_main.imshow(Main, aspect='equal') plt.colorbar(im_main, cax=ax_main_cbar) # 绘制Top图和水平色条 im_top = ax_top.imshow(Top, aspect='auto') # aspect='auto'让Top图自动适配宽度,和Main对齐 plt.colorbar(im_top, cax=ax_top_cbar, orientation='horizontal') # 绘制Left图和对应色条 im_left = ax_left.imshow(Left, aspect='auto') # aspect='auto'让Left图自动适配高度,和Main对齐 plt.colorbar(im_left, cax=ax_left_cbar) # 隐藏冗余刻度,让布局更清爽 for ax in [ax_main, ax_top, ax_left]: ax.set_xticks([]) ax.set_yticks([]) for ax in [ax_main_cbar, ax_top_cbar, ax_left_cbar]: ax.tick_params(labelsize=8) plt.tight_layout() plt.show()
关键调整说明
- GridSpec布局:通过
height_ratios和width_ratios精准控制每个区域的大小比例,比append_axes更直观,避免了嵌套divider带来的贴合问题。 - aspect参数:给Top和Left图设置
aspect='auto',让它们自动适配所在坐标轴的尺寸,保证和Main图完美对齐。 - 间距控制:
wspace和hspace设为极小值,实现各个子图和色条的紧密贴合。 - 可扩展性:这个布局很容易嵌入到其他绘图中——只要把当前的GridSpec作为子布局嵌套进更大的GridSpec就行。
如果你非要用axes_grid1,也可以把append_axes的size改成百分比(比如size="10%"),同时设置pad=0,但GridSpec的方式明显更易维护和调整。
内容的提问来源于stack exchange,提问作者Josh.F
相关产品推荐
相关产品推荐

