# Matplotlib 教程 - 在图中放置文本

Jinku Hu 2024年2月15日

## 坐标轴 `Text`

``````matplotlib.axes.Axes.text(x, y, s, fontdict=None, withdash=False, **kwargs)
``````

`x, y` `scalars` 放置文字的位置
`s` `str` 文字
`fontdict` `dictionary` 覆盖默认文本字体属性的字典

## 坐标轴 `Text` 基本示例

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

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

fig, ax = plt.subplots(1, figsize=(6, 4.5))
ax.plot(x, y, "r")
ax.text(2.0, 9.5, "Peak Value", fontsize=14)

ax.grid(True)

plt.show()
``````

## 坐标轴 `Text` 旋转

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

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

fig, ax = plt.subplots(1, figsize=(6, 4.5))
ax.plot(x, y, "r")
ax.text(1.3, 9.0, "Peak Value", fontsize=16, rotation=270)

ax.grid(True)

plt.show()
``````

## 坐标轴 `Text` 旋转角度说明

``````import matplotlib.pyplot as plt
import numpy as np

for x in range(8):
angle = 45 * x
ax.text(0.5 + x, 0.5, "{} degree".format(angle), props, rotation=angle)
ax.scatter(x + 0.5, 0.5, color="r")

ax.set_yticks([0, 0.5, 1])
ax.set_xlim(0, 8)
ax.grid(True)

# the text bounding box
bbox = {"fc": "0.8", "pad": 0}

fig, axs = plt.subplots(1, 1, figsize=(8, 3))

addtext(axs, {"ha": "center", "va": "center", "bbox": bbox})
axs.set_xticks(np.arange(0, 8.1, 0.5), [])
axs.set_ylabel("center / center")

plt.show()
``````

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