Matplotlib中如何为指定子图(第2与3、6与7)设置间距?
实现Matplotlib指定子图间的额外间距
问题说明
需要在8个Matplotlib子图的第2与第3个、第6与第7个之间设置额外间距,但手动设置子图位置的方式无法达到预期效果,还存在子图超出画布的问题。
修改后的代码
import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec # 创建画布 fig = plt.figure(figsize=(20, 18)) # 定义GridSpec:2行5列,第3列作为额外间距(宽度比例是其他列的2倍) gs = GridSpec(2, 5, width_ratios=[1, 1, 2, 1, 1]) # 第一行子图 ax1 = fig.add_subplot(gs[0, 0]) ax1.plot(np.random.rand(10)) ax1.set_title('Subplot 1') ax2 = fig.add_subplot(gs[0, 1]) ax2.plot(np.random.rand(10)) ax2.set_title('Subplot 2') # 跳过第3列,作为2和3子图之间的额外间距 ax3 = fig.add_subplot(gs[0, 3]) ax3.plot(np.random.rand(10)) ax3.set_title('Subplot 3') ax4 = fig.add_subplot(gs[0, 4]) ax4.plot(np.random.rand(10)) ax4.set_title('Subplot 4') # 第二行子图 ax5 = fig.add_subplot(gs[1, 0]) ax5.plot(np.random.rand(10)) ax5.set_title('Subplot 5') ax6 = fig.add_subplot(gs[1, 1]) ax6.plot(np.random.rand(10)) ax6.set_title('Subplot 6') # 跳过第3列,作为6和7子图之间的额外间距 ax7 = fig.add_subplot(gs[1, 3]) ax7.plot(np.random.rand(10)) ax7.set_title('Subplot 7') ax8 = fig.add_subplot(gs[1, 4]) ax8.plot(np.random.rand(10)) ax8.set_title('Subplot 8') # 自动调整子图布局,避免标题、标签重叠 fig.tight_layout() plt.show()
代码说明
- GridSpec布局:通过
GridSpec将画布分为2行5列,设置width_ratios让第3列宽度是其他列的2倍,以此作为指定位置的额外间距,无需手动计算子图坐标。 - 避免布局冲突:原代码中手动设置
set_position会和tight_layout、subplots_adjust的布局规则冲突,导致子图位置混乱甚至超出画布,使用GridSpec可以统一管理布局。 - 自动优化布局:
tight_layout会自动调整子图的标题、坐标轴标签位置,避免重叠问题。
内容的提问来源于stack exchange,提问作者Tayba Khan
相关产品推荐
相关产品推荐

