You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Matplotlib子图中Y轴标签的居中位置

调整Matplotlib子图Y轴标签与Y轴完美居中的方法

要让Y轴标签和Y轴垂直居中,这里提供两种实用方法,结合你的代码示例说明:

方法1:通过labelpad参数微调间距

直接在plt.ylabel()中添加labelpad参数,控制标签与Y轴的距离。如果需要向下微调,可设置负数(数值大小根据图表尺寸调整,比如labelpad=-10):

import matplotlib.pyplot as plt
from numpy import random

sizes=22

x1 = random.randint(2000, size=(125))
x2 = random.randint(1000, size=(125))
plt.subplot(2, 3, 1)
plt.plot(x1, color='red')
plt.plot(x2, color='blue')
plt.yticks(fontsize=sizes)
plt.xticks(fontsize=sizes)
plt.title("Plot 1", fontsize=sizes)
# 添加labelpad参数调整位置,数值可根据实际效果修改
plt.ylabel('Y-Axis', fontsize=sizes, labelpad=-10)

# 修正原代码错误:pp.legend改为plt.legend
x1 = random.randint(2000, size=(125))
x2 = random.randint(1000, size=(125))
plt.subplot(2, 3, 2)
plt.plot(x1, label="class 1", color='red')
plt.plot(x2, label="class 2", color='blue')
plt.yticks(fontsize=sizes)
plt.xticks(fontsize=sizes)
leg = plt.legend(loc='lower center',fontsize=sizes, bbox_to_anchor=[0.5, 1.25], ncol=2)
plt.title("Plot 2", fontsize=sizes)

x1 = random.randint(2000, size=(125))
x2 = random.randint(1000, size=(125))
plt.subplot(2, 3, 3)
plt.plot(x1, color='red')
plt.plot(x2, color='blue')
plt.yticks(fontsize=sizes)
plt.xticks(fontsize=sizes)
plt.title("Plot 3", fontsize=sizes)

x1 = random.randint(2000, size=(125))
x2 = random.randint(1000, size=(125))
plt.subplot(2, 3, 4)
plt.plot(x1, color='red')
plt.plot(x2, color='blue')
plt.yticks(fontsize=sizes)
plt.xticks(fontsize=sizes)
plt.title("Plot 4", fontsize=sizes)

x1 = random.randint(2000, size=(125))
x2 = random.randint(1000, size=(125))
plt.subplot(2, 3, 5)
plt.plot(x1, color='red')
plt.plot(x2, color='blue')
plt.yticks(fontsize=sizes)
plt.xticks(fontsize=sizes)
plt.title("Plot 5", fontsize=sizes)
plt.xlabel('X-Axis', fontsize=sizes)

x1 = random.randint(2000, size=(125))
x2 = random.randint(1000, size=(125))
plt.subplot(2, 3, 6)
plt.plot(x1, color='red')
plt.plot(x2, color='blue')
plt.yticks(fontsize=sizes)
plt.xticks(fontsize=sizes)
plt.title("Plot 6", fontsize=sizes)

plt.rcParams['figure.figsize'] = (18, 14)
plt.tight_layout()
plt.show() 

方法2:获取轴对象精确控制标签位置

如果需要更精准的对齐,可先获取当前子图的轴对象,通过set_ylabel设置垂直对齐方式,或用yaxis.set_label_coords指定坐标:

# 在第一个子图中替换plt.ylabel为以下代码:
ax = plt.gca()
# 设置垂直对齐为center,水平对齐为right,确保标签与Y轴居中
ax.set_ylabel('Y-Axis', fontsize=sizes, va='center', ha='right')
# 或者用坐标精确调整,x为水平偏移(负数向左移),y为垂直位置(0.5是轴的垂直中点)
# ax.yaxis.set_label_coords(-0.1, 0.5)

注意事项

  • 原代码中pp.legend是错误写法,需改为plt.legend,否则会触发报错,已在示例中修正。
  • labelpad的数值和坐标参数需要根据图表尺寸、字体大小微调,直到达到你想要的完美居中效果。

内容的提问来源于stack exchange,提问作者xnok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:45:38