如何让Matplotlib网格布局中底行子图居中且保持尺寸一致?
实现Matplotlib上3下2且底行子图居中的布局(保持子图尺寸一致)
要实现顶部3个子图、底部2个子图居中且所有子图尺寸完全一致的效果,以下两种方案可以直接解决问题:
方案一:基于原有代码调整子图位置
在你现有代码的基础上,删除多余子图后,手动调整底行两个子图的位置,让它们整体居中:
import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 3, figsize=(10,5), sharey=True) # 绘制所有子图 for i in range(5): row, col = divmod(i, 3) axs[row, col].plot([0, 1], [0, i]) # 删除右下角的空图 fig.delaxes(axs[1, 2]) # 获取底行子图的位置参数 box_left = axs[1, 0].get_position() box_right = axs[1, 1].get_position() # 计算偏移量:总剩余空白宽度为1减去两个子图的宽度和,均分至左右两侧 offset = (1 - (box_left.width + box_right.width)) / 2 # 重新设置子图位置,向右偏移offset实现居中 axs[1, 0].set_position([box_left.x0 + offset, box_left.y0, box_left.width, box_left.height]) axs[1, 1].set_position([box_right.x0 + offset, box_right.y0, box_right.width, box_right.height]) plt.tight_layout() plt.show()
方案二:使用GridSpec精确控制布局
通过GridSpec直接定义子图的网格位置,逻辑更清晰可控:
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.figure(figsize=(10, 5)) # 创建2行3列的网格,设置行/列间距,保证所有子图尺寸一致 gs = GridSpec(2, 3, figure=fig, wspace=0.2, hspace=0.3) # 第一行的三个子图,各占一个网格单元 ax_top1 = fig.add_subplot(gs[0, 0]) ax_top2 = fig.add_subplot(gs[0, 1]) ax_top3 = fig.add_subplot(gs[0, 2]) # 第二行的两个子图,先占据左侧两个网格单元 ax_bottom1 = fig.add_subplot(gs[1, 0]) ax_bottom2 = fig.add_subplot(gs[1, 1]) # 绘制数据 for idx, ax in enumerate([ax_top1, ax_top2, ax_top3, ax_bottom1, ax_bottom2]): ax.plot([0, 1], [0, idx]) # 获取单个子图的宽度,计算偏移量(空出一个网格单元的一半宽度) single_width = ax_bottom1.get_position().width offset = single_width / 2 # 调整底行子图位置实现居中 ax_bottom1.set_position([ax_bottom1.get_position().x0 + offset, ax_bottom1.get_position().y0, single_width, ax_bottom1.get_position().height]) ax_bottom2.set_position([ax_bottom2.get_position().x0 + offset, ax_bottom2.get_position().y0, single_width, ax_bottom2.get_position().height]) plt.show()
内容的提问来源于stack exchange,提问作者guskenny83
相关产品推荐
相关产品推荐

