# Matplotlib 教程 - 坐标轴标题

Jinku Hu 2024年2月15日

## Matplotlib 坐标轴标题

``````matplotlib.pyplot.title(label, fontdict=None, loc=None, **kwargs)
``````

`label` `str` 标签文字
`fontdict` `dict` 标签文字字体字典，例如字体系列、颜色、粗细和大小
`loc` `str` 标题的位置。它具有三个选项，`{'center', 'left', 'right'}`。默认选项是 `center`
``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.figure(figsize=(4, 3))

plt.plot(x, y, "r")
plt.xlabel(
"Time (s)",
size=16,
)
plt.ylabel("Value", size=16)

plt.title(
"Title Example",
fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 18},
)

plt.grid(True)

plt.show()
``````

``````plt.title(
"Title Example",
fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 18},
)
``````

## 坐标轴上的多个标题

``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.figure(figsize=(8, 6))

plt.plot(x, y, "r")
plt.xlabel(
"Time (s)",
size=16,
)
plt.ylabel("Value", size=16)

plt.title(
"Left title",
fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 16},
loc="left",
)

plt.title(
"Center title",
fontdict={"family": "monospace", "color": "red", "weight": "bold", "size": 16},
loc="center",
)

plt.title(
"Right title",
fontdict={"family": "fantasy", "color": "black", "weight": "bold", "size": 16},
loc="right",
)

plt.grid(True)

plt.show()
``````

## 将坐标轴标题放置在绘图内部

``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.figure(figsize=(6, 4.5))

plt.plot(x, y, "r")
plt.xlabel("Time (s)", size=16)
plt.ylabel("Value", size=16)

plt.title(
"Title Example",
position=(0.5, 0.9),
fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 16},
)

plt.show()
``````

DelftStack.com 创始人。Jinku 在机器人和汽车行业工作了8多年。他在自动测试、远程测试及从耐久性测试中创建报告时磨练了自己的编程技能。他拥有电气/电子工程背景，但他也扩展了自己的兴趣到嵌入式电子、嵌入式编程以及前端和后端编程。