matplotlib中如何移除带共享色条的热力图子图上下多余空白
问题说明
以下代码用于在同一行绘制3个热力图,并在热力图右侧添加共享colorbar:
import numpy as np import matplotlib.pyplot as plt num_rows = 100 num_cols = 200 noise_array_1 = np.random.rand(num_rows, num_cols) noise_array_2 = np.random.rand(num_rows, num_cols) noise_array_3 = np.random.rand(num_rows, num_cols) figure, axes = plt.subplots(1, 3) figure.set_dpi(200) figure.suptitle("Heat maps title") heatmap = axes[0].imshow(noise_array_1, cmap="jet") heatmap = axes[1].imshow(noise_array_2, cmap="jet") heatmap = axes[2].imshow(noise_array_3, cmap="jet") figure.subplots_adjust(right=0.8) colorbar_axes = figure.add_axes([0.85, 0.1, 0.01, 0.3]) figure.colorbar(heatmap, cax=colorbar_axes) plt.show()
运行后绘图区域上下存在大量多余空白,尝试移除空白时容易打乱共享colorbar位置,需要实现两个目标:
- 移除子图上下方的多余空白
- 移除空白后正确定位共享colorbar位置
原始运行效果:
实现方案
核心思路是放弃手动硬编码colorbar的归一化坐标,使用axes_grid1工具包的轴分割方法自动绑定colorbar与热力图的位置关系,再通过边距参数精确控制空白范围,修正后代码如下:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable num_rows = 100 num_cols = 200 noise_array_1 = np.random.rand(num_rows, num_cols) noise_array_2 = np.random.rand(num_rows, num_cols) noise_array_3 = np.random.rand(num_rows, num_cols) figure, axes = plt.subplots(1, 3, dpi=200) figure.suptitle("Heat maps title", y=0.98) # 统一三个热力图的色值范围,保证共享colorbar映射准确 vmin = min(arr.min() for arr in [noise_array_1, noise_array_2, noise_array_3]) vmax = max(arr.max() for arr in [noise_array_1, noise_array_2, noise_array_3]) for ax, arr in zip(axes, [noise_array_1, noise_array_2, noise_array_3]): im = ax.imshow(arr, cmap="jet", vmin=vmin, vmax=vmax) # 按需隐藏坐标轴刻度 ax.set_xticks([]) ax.set_yticks([]) # 基于最右侧子图自动生成colorbar轴,高度与热力图完全对齐 divider = make_axes_locatable(axes[-1]) cax = divider.append_axes("right", size="2%", pad=0.15) figure.colorbar(im, cax=cax) # 精确控制四周边距,消除上下多余空白 figure.subplots_adjust(top=0.92, bottom=0.02, left=0.02, right=0.92, wspace=0.1) plt.show()
方案说明
- 上下多余空白通过
subplots_adjust的top和bottom参数直接控制,可根据标题大小微调数值 - colorbar位置通过轴分割逻辑自动绑定到最右侧热力图,调整边距时不会出现错位
- 额外统一了三个热力图的色值映射范围,修正了原始代码中仅以最后一个热力图色值范围生成colorbar导致的前两个热力图色标不准的问题
内容的提问来源于stack exchange,提问作者indigoblue
相关产品推荐
相关产品推荐

