GridSpec布局下,如何使带底部Colorbar的Imshow与左侧图等高?
解决Matplotlib双Imshow子图高度不一致问题(带底部Colorbar)
当给右侧子图添加底部Colorbar时,Matplotlib会自动压缩右侧子图高度来容纳Colorbar,导致左右两个Imshow图高度错位。可以通过以下两种方法解决:
方法一:用GridSpec手动分配空间
把右侧区域拆分为上下两部分,上方放子图,下方放Colorbar,确保左侧子图高度与右侧子图区域完全对齐:
import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec cm = 1/2.54 fig = plt.figure() fig.set_size_inches(21*cm,29.7*cm) # 主网格:1行2列,左右列宽度一致 gs_main = GridSpec(1, 2, figure=fig, width_ratios=[1,1]) # 右侧子网格:2行1列,子图占大部分,Colorbar占小部分 gs_right = GridSpecFromSubplotSpec(2, 1, subplot_spec=gs_main[0,1], height_ratios=[20,1]) data1 = np.random.rand(100,1000) data2 = np.random.rand(100,1000) # 左侧子图 ax_left = fig.add_subplot(gs_main[0,0]) img_left = ax_left.imshow(data1, aspect='auto') # 右侧子图(占用右侧网格的上半部分) ax_right = fig.add_subplot(gs_right[0,0]) img_right = ax_right.imshow(data2, aspect='auto') # Colorbar放在右侧网格的下半部分 cax = fig.add_subplot(gs_right[1,0]) fig.colorbar(img_right, cax=cax, orientation='horizontal') plt.tight_layout() plt.show()
方法二:用make_axes_locatable自动拆分轴
这个工具可以从右侧子图的轴空间中自动拆分出Colorbar的位置,无需手动调整网格,更简洁:
import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec from mpl_toolkits.axes_grid1 import make_axes_locatable cm = 1/2.54 fig = plt.figure() fig.set_size_inches(21*cm,29.7*cm) gs = GridSpec(1,2,figure=fig) data1 = np.random.rand(100,1000) data2 = np.random.rand(100,1000) ax_left = fig.add_subplot(gs[:,0]) img_left = ax_left.imshow(data1, aspect='auto') ax_right = fig.add_subplot(gs[:,1]) img_right = ax_right.imshow(data2, aspect='auto') # 拆分右侧轴,在底部创建Colorbar的轴空间 divider = make_axes_locatable(ax_right) # size设置Colorbar高度占比,pad设置与子图的间距 cax = divider.append_axes("bottom", size="5%", pad=0.1) fig.colorbar(img_right, cax=cax, orientation="horizontal") plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Mo0nKizz
相关产品推荐
相关产品推荐

