现在位置: 首页 > Matplotlib 教程 > 正文

Matplotlib 标题与标签函数


Matplotlib 参考文档 Matplotlib 参考文档

Matplotlib 提供了一组函数用于设置图表的标题、坐标轴标签和总标题,是让图表完整可读的基础。

涉及函数

函数功能对应 Axes 方法
title()设置 Axes 标题ax.set_title()
xlabel() / ylabel()设置 x/y 轴标签ax.set_xlabel() / ax.set_ylabel()
suptitle()设置 Figure 总标题fig.suptitle()
supxlabel() / supylabel()设置 Figure 级别 x/y 轴标签fig.supxlabel() / fig.supylabel()

函数定义

matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None,
    *, y=None, **kwargs)
matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *,
    loc=None, **kwargs)
matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None, *,
    loc=None, **kwargs)
matplotlib.pyplot.suptitle(t, **kwargs)
matplotlib.pyplot.supxlabel(t, **kwargs)
matplotlib.pyplot.supylabel(t, **kwargs)

常用参数

参数说明
label / xlabel / ylabel / t文本内容(必填)
fontsize / size字体大小,如 14、'large'、'x-large'
fontweight / weight字重:'normal'、'bold'、'light'
color文本颜色
fontdict字体属性字典,如 {'fontsize':14, 'color':'blue'}
loc对齐位置:'center'(默认)、'left'、'right'
pad / labelpad文本与坐标轴/图表边缘的间距(以点为单位)
y(title 专用)标题的垂直位置(Axes 坐标,1.0 为顶部)

Axes 对象的方法命名以 set_ 开头,如 ax.set_title()ax.set_xlabel(),这是面向对象接口的推荐写法。


使用示例

示例 1:基本标题与标签

实例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x) * np.exp(-x/5)

fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

ax.plot(x, y, 'steelblue', linewidth=2)

# 设置标题(Axes 级别)
ax.set_title('Damped Sine Wave', fontsize=14, fontweight='bold')

# 设置轴标签
ax.set_xlabel('Time (seconds)', fontsize=12)
ax.set_ylabel('Amplitude (V)', fontsize=12)

ax.grid(True, alpha=0.3)
plt.show()

示例 2:Figure 总标题 + 轴标签

实例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, axes = plt.subplots(2, 2, figsize=(10, 8),
                          layout='constrained')

# 每个子图有自己的标题
axes[0, 0].plot(x, np.sin(x)); axes[0, 0].set_title('sin(x)')
axes[0, 1].plot(x, np.cos(x)); axes[0, 1].set_title('cos(x)')
axes[1, 0].plot(x, np.sin(2*x)); axes[1, 0].set_title('sin(2x)')
axes[1, 1].plot(x, np.cos(2*x)); axes[1, 1].set_title('cos(2x)')

# Figure 级别总标题
fig.suptitle('Trigonometric Functions Overview',
             fontsize=16, fontweight='bold', y=1.02)

# Figure 级别轴标签(居中于所有子图)
fig.supxlabel('x (radians)', fontsize=13)
fig.supylabel('Amplitude', fontsize=13)

plt.show()

示例 3:标题位置与样式

实例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
                                 layout='constrained')

# 左图:左对齐标题
ax1.plot(x, np.sin(x), 'steelblue')
ax1.set_title('Left-aligned Title',
              loc='left',                # 左对齐
              fontsize=12,
              color='steelblue')
ax1.set_xlabel('X-axis', fontsize=10, color='gray')

# 右图:右对齐标题
ax2.plot(x, np.cos(x), 'coral')
ax2.set_title('Right-aligned Title',
              loc='right',               # 右对齐
              fontsize=12,
              color='coral',
              fontstyle='italic')
ax2.set_ylabel('Y-axis', fontsize=10, color='gray',
               rotation=0, labelpad=20)  # 标签不旋转

plt.show()

示例 4:LaTeX 数学公式标题

实例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 5, 200)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
                                 layout='constrained')

# 高斯分布
sigma, mu = 1.0, 0.0
y1 = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2/(2*sigma**2))
ax1.plot(x, y1, 'steelblue', linewidth=2)

# 使用 LaTeX 公式作为标题
ax1.set_title(
    r'$f(x) = frac{1}{sigmasqrt{2pi}}'
    r'expleft(-frac{(x-mu)^2}{2sigma^2}right)$',
    fontsize=12)

# 多项式
y2 = x**3 - 3*x
ax2.plot(x, y2, 'coral', linewidth=2)
ax2.set_title(r'$f(x) = x^3 - 3x$', fontsize=14)
ax2.axhline(y=0, color='gray', linewidth=0.5)

for ax in [ax1, ax2]:
    ax.set_xlabel('x')
    ax.grid(True, alpha=0.3)

fig.suptitle('Functions with LaTeX Titles', fontsize=14,
             fontweight='bold')
plt.show()
print("runoob: LaTeX titles displayed")

常见问题

title() 和 suptitle() 的区别?

title()(或 ax.set_title()):设置在单个 Axes 上方的标题。

suptitle()(或 fig.suptitle()):设置在整个 Figure 顶部的总标题,覆盖所有子图。

如何让标题支持中文?

设置字体:plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['font.family'] = 'sans-serif'


Matplotlib 参考文档 Matplotlib 参考文档