如何在Matplotlib的2行4列子图中仅为左右两组添加专属水平间距
如何在Matplotlib的2行4列子图中仅为左右两组添加专属水平间距
嘿,我完全懂你的需求——就是想在左右两组子图中间单独拉开一段空隙,而不是让所有子图之间的间距都跟着变大对吧?确实直接调全局的wspace参数行不通,不过咱们可以用Matplotlib的GridSpec玩点小技巧,下面给你两种实用的解决方法:
方法一:拆分GridSpec列,用空白列做间隔
这种方法是把原来的列布局拆分出一个专门的空白列,用来充当左右两组的间距,操作起来很简单:
import matplotlib.pyplot as plt fig = plt.figure(figsize=(14, 12)) # 把列分成6份:左2列、中间0.2宽度的空白列、右2列,最后一列设0避免右侧留白 gs = fig.add_gridspec(2, 6, hspace=0, width_ratios=[1, 1, 0.2, 1, 1, 0]) # 左边四个子图 ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1]) ax3 = fig.add_subplot(gs[1, 0]) ax4 = fig.add_subplot(gs[1, 1]) # 右边四个子图 ax5 = fig.add_subplot(gs[0, 3]) ax6 = fig.add_subplot(gs[0, 4]) ax7 = fig.add_subplot(gs[1, 3]) ax8 = fig.add_subplot(gs[1, 4]) # 绘图逻辑和你原来的代码一致 for ax in [ax1, ax2, ax3, ax4]: ax.plot([0, 1], [0, 1]) for ax in [ax5, ax6, ax7, ax8]: ax.plot([0, 1], [1, 0]) # 隐藏不需要的刻度标签 axes_to_modify = [ax2, ax4, ax6, ax8] for ax in axes_to_modify: ax.set_xlabel('') ax.set_ylabel('') ax.set_xticklabels([]) ax.set_yticklabels([]) plt.show()
你可以调整width_ratios里的中间值(现在是0.2)来控制空隙的宽窄,数值越大间距就越宽。
方法二:用两个独立GridSpec分别创建左右组
如果想更灵活地控制两组子图的位置,比如单独调整每组的左右边距,那用两个独立的GridSpec会更合适:
import matplotlib.pyplot as plt fig = plt.figure(figsize=(14, 12)) # 左边组的GridSpec:控制在画布左侧0.05到0.45的区域 gs_left = fig.add_gridspec(2, 2, left=0.05, right=0.45, hspace=0, wspace=0) # 右边组的GridSpec:控制在画布右侧0.55到0.95的区域,和左边组留出0.1的空隙 gs_right = fig.add_gridspec(2, 2, left=0.55, right=0.95, hspace=0, wspace=0) # 左边子图 ax1 = fig.add_subplot(gs_left[0,0]) ax2 = fig.add_subplot(gs_left[0,1]) ax3 = fig.add_subplot(gs_left[1,0]) ax4 = fig.add_subplot(gs_left[1,1]) # 右边子图 ax5 = fig.add_subplot(gs_right[0,0]) ax6 = fig.add_subplot(gs_right[0,1]) ax7 = fig.add_subplot(gs_right[1,0]) ax8 = fig.add_subplot(gs_right[1,1]) # 绘图和隐藏刻度的逻辑不变 for ax in [ax1, ax2, ax3, ax4]: ax.plot([0, 1], [0, 1]) for ax in [ax5, ax6, ax7, ax8]: ax.plot([0, 1], [1, 0]) axes_to_modify = [ax2, ax4, ax6, ax8] for ax in axes_to_modify: ax.set_xlabel('') ax.set_ylabel('') ax.set_xticklabels([]) ax.set_yticklabels([]) plt.show()
这里通过left和right参数直接定义每组子图在画布上的位置,中间的空隙就是两组right和left的差值(0.55-0.45=0.1),你可以直接修改这些数值来精准控制间距。
两种方法都能完美实现你的需求,选哪个就看你更看重布局的简洁性还是灵活性啦~
备注:内容来源于stack exchange,提问作者James Lane




