如何让Matplotlib子图的Y轴标签与子图中部对齐?
解决Matplotlib子图水平ylabel对齐错位问题
针对你遇到的子图水平ylabel错位问题,核心是利用**子图相对坐标(transAxes)**定位标签,确保所有标签自动对齐到子图底部,以下是两种实用解决方式:
方法一:调整现有ylabel的对齐与位置
修改set_ylabel的对齐参数,并用子图相对坐标指定标签位置:
import numpy as np import matplotlib.pyplot as plt data = np.random.rand(10, 1000) dogs = ["woof", "bark", "bowwow"] fig, axs = plt.subplots(10, figsize=(8, 6)) # 可按需调整画布大小适配标签 for i in range(10): axs[i].scatter(np.linspace(0, 1, 1000), np.linspace(0,1,1000)*0, 2000, c=data[i, :], marker="|", cmap='inferno') axs[i].set_frame_on(False) axs[i].set_yticklabels([]) axs[i].set_xticklabels([]) axs[i].set_xticks([]) axs[i].set_yticks([]) # 设置垂直对齐为底部,确保文本底部与子图底部对齐 axs[i].set_ylabel(dogs[i%3], rotation='horizontal', va='bottom') # transAxes表示坐标相对子图:(0,0)是子图左下角,x=-0.05为向左偏移5%子图宽度 axs[i].yaxis.set_label_coords(-0.05, 0, transform=axs[i].transAxes) plt.tight_layout() # 自动调整子图间距,避免标签被截断 plt.show()
方法二:用annotate替代ylabel(更灵活)
直接使用annotate添加标签,明确指定位置和对齐规则:
import numpy as np import matplotlib.pyplot as plt data = np.random.rand(10, 1000) dogs = ["woof", "bark", "bowwow"] fig, axs = plt.subplots(10, figsize=(8, 6)) for i in range(10): axs[i].scatter(np.linspace(0, 1, 1000), np.linspace(0,1,1000)*0, 2000, c=data[i, :], marker="|", cmap='inferno') axs[i].set_frame_on(False) axs[i].set_yticklabels([]) axs[i].set_xticklabels([]) axs[i].set_xticks([]) axs[i].set_yticks([]) # 用annotate添加标签:xy指定相对子图的位置,va='bottom'确保文本底部对齐子图底部 axs[i].annotate( dogs[i%3], xy=(-0.05, 0), xycoords=axs[i].transAxes, va='bottom', ha='right' # 文本右对齐,统一标签位置 ) plt.tight_layout() plt.show()
关键说明
transAxes是子图专属的相对坐标系统,(0,0)对应子图左下角,(1,1)对应右上角,无论子图在画布的哪个位置,该坐标都相对子图自身,因此能实现自动对齐。va='bottom'强制文本底部与指定的y坐标(子图底部y=0)对齐,从根源解决错位问题。plt.tight_layout()会自动调整子图间距,避免标签被画布边缘截断。
内容的提问来源于stack exchange,提问作者Ned Ryerson
相关产品推荐
相关产品推荐

