一、Figure和Axes上的文本
Matplotlib 提供了两套 API 用于添加文本,功能完全对应,仅调用方式不同:
表格
| pyplot API | OO API | 功能描述 |
|---|---|---|
text |
Axes.text() |
在 Axes(子图) 的任意坐标位置添加文本 |
title |
Axes.set_title() |
为 Axes 添加标题 |
figtext |
Figure.text() |
在 Figure(画布) 的任意位置添加文本(不依赖子图坐标) |
suptitle |
Figure.suptitle() |
为整个 Figure 添加总标题 |
xlabel |
Axes.set_xlabel() |
为 Axes 的 X 轴添加标签 |
ylabel |
Axes.set_ylabel() |
为 Axes 的 Y 轴添加标签 |
annotate |
Axes.annotate() |
向 Axes 添加带可选箭头的标注(常用于标注数据点) |
二、核心函数 text() 详解
1. 函数定义
- pyplot API :
matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs) - OO API :
Axes.text(self, x, y, s, fontdict=None, **kwargs)
2. 核心参数
表格
| 参数 | 说明 |
|---|---|
x, y |
文本放置的坐标(基于 Axes 的数据坐标系) |
s |
要添加的文本内容(支持 LaTeX 数学公式) |
fontdict |
可选字典,用于批量覆盖默认文本样式(如字体、颜色、大小等) |
**kwargs |
单独指定的样式参数,优先级高于 fontdict |
3. fontdict 常用样式参数
表格
| 参数 | 说明 | 可选值 / 示例 |
|---|---|---|
family |
字体类型 | 'SimSun'(华文宋体)、'Times New Roman'、'serif'、'sans-serif' 等 |
color/c |
字体颜色 | 'red'、'blue'、'purple'、'navy' 等 |
weight/fontweight |
字体粗细 | 'normal'、'bold'、'light' 等 |
size/fontsize |
字体大小 | 数值(如 16)、'large'、'x-large' 等 |
alpha |
透明度 | 0(完全透明)~ 1(完全不透明) |
backgroundcolor |
文本背景色 | 同字体颜色可选值 |
rotation |
旋转角度 | 数值(逆时针)、'vertical'(90°)、'horizontal'(0°) |
ha/horizontalalignment |
水平对齐 | 'left'、'center'、'right' |
va/verticalalignment |
垂直对齐 | 'top'、'center'、'bottom'、'baseline' |
bbox |
文本外框 | 字典,如 {'boxstyle':'round', 'facecolor':'#fff', 'alpha':0.8} |
三、完整实战代码(可直接运行)
python
运行
import numpy as np
import matplotlib.pyplot as plt
# ---------------------- 1. 定义4种字体样式 ----------------------
# 样式1:华文宋体、紫色、16号、0.7透明度
font1 = {
'family': 'SimSun',
'alpha': 0.7,
'color': 'purple',
'weight': 'normal',
'size': 16
}
# 样式2:Times New Roman、红色、16号
font2 = {
'family': 'Times New Roman',
'color': 'red',
'weight': 'normal',
'size': 16
}
# 样式3:衬线字体、蓝色、加粗、14号
font3 = {
'family': 'serif',
'color': 'blue',
'weight': 'bold',
'size': 14
}
# 样式4:Calibri、藏青色、17号
font4 = {
'family': 'Calibri',
'color': 'navy',
'weight': 'normal',
'size': 17
}
# ---------------------- 2. 生成数据并绘图 ----------------------
# 定义衰减震荡函数:y = cos(2πx) * exp(-x/3)
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2 * np.pi * x) * np.exp(-x/3)
# 绘制虚线曲线
plt.plot(x, y, '--')
# ---------------------- 3. 添加各类文本标注 ----------------------
# 1. 子图标题
plt.title('震荡曲线', fontdict=font1)
# 2. 在坐标(2, 0.65)处添加数学公式(LaTeX语法)
plt.text(2, 0.65, r'$\cos(2 \pi x) \exp(-x/3)$', fontdict=font2)
# 3. X轴标签
plt.xlabel('Y=time (s)', fontdict=font3)
# 4. Y轴标签
plt.ylabel('X=voltage(mv)', fontdict=font4)
# ---------------------- 4. 调整布局并显示 ----------------------
# 调整左侧边距,避免Y轴标签被截断
plt.subplots_adjust(left=0.15)
plt.show()
四、运行效果解读
代码运行后生成的图表包含以下关键元素:
- 标题 :
震荡曲线(紫色华文宋体,位于图表顶部) - 数学公式标注 :
cos(2πx)exp(-x/3)(红色 Times New Roman,标注在曲线旁) - 坐标轴标签 :
- X 轴:
Y=time (s)(蓝色加粗衬线字体) - Y 轴:
X=voltage(mv)(藏青色 Calibri 字体)
- X 轴:
- 曲线 :蓝色虚线,呈现衰减震荡的形态(振幅随 x 增大逐渐减小)
五、关键知识点拓展
1. LaTeX 数学公式支持
Matplotlib 原生支持 LaTeX 语法,只需用 r'$...$' 包裹公式即可渲染,例如:
r'$\alpha$'→ αr'$\sqrt{x^2+y^2}$'→ √(x²+y²)r'$\sum_{i=1}^{n} x_i$'→ ∑(i=1 到 n) x_i
2. 坐标系说明
text()默认使用 数据坐标系 (即x,y对应图表的数值坐标)- 若要使用相对坐标系 (0-1,基于 Axes/Figure 的比例),可添加参数:
transform=ax.transAxes(Axes 相对坐标)transform=fig.transFigure(Figure 相对坐标)
3. 中文显示问题
若运行代码出现中文乱码,需在代码开头添加以下配置:
python
运行
plt.rcParams['font.sans-serif'] = ['SimSun'] # 替换为你的中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示异常
六、常见使用场景
表格
| 场景 | 推荐 API | 示例 |
|---|---|---|
| 子图标题 | title() / set_title() |
plt.title('实验数据', fontsize=18) |
| 数据点标注 | annotate() |
plt.annotate('峰值', xy=(1, 1), xytext=(1.2, 1.2), arrowprops=dict(arrowstyle='->')) |
| 画布总标题 | suptitle() |
plt.suptitle('2025年实验报告', y=0.98) |
| 任意位置文本 | text() / figtext() |
plt.figtext(0.5, 0.02, '数据来源:实验室', ha='center') |
七、可直接修改的参数建议
你可以直接修改代码中的以下部分,快速调整样式:
- 修改字体 :替换
fontdict中的family值(如'Microsoft YaHei'、'Arial') - 修改颜色 :替换
color值(支持英文、十六进制如'#FF5733'、RGB 元组) - 修改公式位置 :调整
plt.text()的x,y坐标 - 添加外框 :在
fontdict中添加'bbox': {'facecolor':'yellow', 'alpha':0.3} - 旋转文本 :添加
'rotation': 45实现 45° 逆时针旋转
如果你需要,我可以帮你补充 annotate() 箭头标注的详细用法 ,或者优化图表的配色、布局,生成更符合论文 / 报告规范的样式。




Matplotlib 标题 / 坐标轴标签 / 画布文本全解析(附完整代码)
这组资料承接上一节,详细讲解了 Matplotlib 中子图标题、画布文本、总标题、坐标轴标签的用法,包含两种 API、核心参数、实战案例与效果展示,下面是结构化梳理与深度解读。
一、核心 API 速查表
表格
| 功能 | pyplot API | OO API | 作用域 | 核心特点 |
|---|---|---|---|---|
| 子图标题 | plt.title() |
Axes.set_title() |
单个 Axes(子图) | 仅作用于当前子图,可控制位置、边距 |
| 画布任意文本 | plt.figtext() |
Figure.text() |
整个 Figure(画布) | 基于画布相对坐标 (0-1),不依赖子图 |
| 画布总标题 | plt.suptitle() |
Figure.suptitle() |
整个 Figure(画布) | 专为总标题设计,默认居中置顶 |
| X 轴标签 | plt.xlabel() |
Axes.set_xlabel() |
单个 Axes(子图) | 绑定 X 轴,可控制与轴的距离、对齐方式 |
| Y 轴标签 | plt.ylabel() |
Axes.set_ylabel() |
单个 Axes(子图) | 绑定 Y 轴,可控制与轴的距离、对齐方式 |
二、各函数详细参数与用法
1. title() / set_title():子图标题
函数定义
- pyplot API:
matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs) - OO API:
Axes.set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
核心参数
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
label |
标题文本内容 | - |
fontdict |
控制标题样式的字典(字体、颜色、大小等) | 内置默认样式(继承 rcParams) |
loc |
水平对齐方式 | 'center',可选'left'/'right' |
pad |
标题与子图顶部的距离(单位:点) | 6 |
y |
标题在子图内的垂直位置(相对坐标 0-1) | 1(紧贴子图顶部) |
**kwargs |
额外文本样式(如rotation、backgroundcolor等) |
- |
默认fontdict样式
python
运行
{
'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'color': rcParams['axes.titlecolor'],
'verticalalignment': 'baseline',
'horizontalalignment': loc
}
2. figtext() / Figure.text():画布任意位置文本
函数定义
- pyplot API:
matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs) - OO API:
Figure.text(self, x, y, s, fontdict=None, **kwargs)
核心参数
表格
| 参数 | 说明 |
|---|---|
x, y |
文本在画布上的位置,默认使用画布相对坐标 (0-1)(0 = 左 / 下,1 = 右 / 上) |
s |
要添加的文本内容 |
fontdict |
文本样式字典 |
**kwargs |
额外样式(如transform可切换坐标系) |
关键特性
- 坐标默认是画布相对坐标,不受子图位置影响,适合添加水印、署名、全局说明等。
- 可通过
transform=ax.transAxes切换为子图相对坐标,或transform=ax.transData切换为数据坐标。
3. suptitle():画布总标题
函数定义
- pyplot API:
matplotlib.pyplot.suptitle(t, **kwargs) - OO API:
Figure.suptitle(self, t, **kwargs)
核心参数
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
t |
总标题文本 | - |
x, y |
画布相对坐标 | x=0.5(水平居中),y=0.95(靠近画布顶部) |
ha/horizontalalignment |
水平对齐 | 'center' |
va/verticalalignment |
垂直对齐 | 'top' |
fontsize/size |
字体大小 | 'large'(继承 rcParams) |
fontweight/weight |
字体粗细 | 'normal' |
适用场景
- 多子图图表的全局总标题,统一整个画布的主题。
4. xlabel()/ylabel():坐标轴标签
函数定义
- pyplot API:
matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)``matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) - OO API:
Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)``Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
核心参数
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
xlabel/ylabel |
坐标轴标签文本 | - |
fontdict |
标签样式字典 | - |
labelpad |
标签与坐标轴的距离(单位:点) | 继承 rcParams |
loc |
标签在轴上的位置 | 'center',可选'left'/'right' |
**kwargs |
额外样式(如rotation、fontproperties等) |
- |
三、完整实战代码(两种样式设置方式)
资料中给出了两种字体样式设置方法 :**kwargs直接传参、FontProperties对象配置,以下是完整可运行代码:
python
运行
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# ---------------------- 1. 生成衰减震荡数据 ----------------------
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) # 衰减余弦函数
# ---------------------- 2. 用FontProperties配置Y轴标签样式 ----------------------
font = FontProperties()
font.set_family('serif') # 衬线字体
font.set_name('Times New Roman') # 具体字体
font.set_style('italic') # 斜体
font.set_size(14) # 字号
font.set_weight('bold') # 加粗
# ---------------------- 3. 创建画布与子图 ----------------------
fig, ax = plt.subplots(figsize=(5, 3))
# 调整底部和左侧边距,避免标签被截断
fig.subplots_adjust(bottom=0.15, left=0.2)
# ---------------------- 4. 绘制曲线 ----------------------
ax.plot(x1, y1)
# ---------------------- 5. 添加坐标轴标签(两种方式) ----------------------
# 方式1:**kwargs直接传参(X轴标签)
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold', color='#000000')
# 方式2:FontProperties对象配置(Y轴标签)
ax.set_ylabel('Damped oscillation [V]', fontproperties=font)
# ---------------------- 6. 可选:添加子图标题、总标题、画布文本 ----------------------
# 子图标题
ax.set_title('Damped Oscillation Curve', loc='center', pad=10, fontsize=12)
# 画布总标题
fig.suptitle('Experiment Data Report', y=0.98, fontsize=14, fontweight='bold')
# 画布底部添加署名(相对坐标)
plt.figtext(0.5, 0.01, 'Data Source: Lab Test', ha='center', fontsize=10, color='gray')
# ---------------------- 7. 显示图表 ----------------------
plt.show()
四、运行效果解读
代码运行后生成的图表包含以下关键元素:
- 曲线 :蓝色衰减震荡曲线,振幅随时间(x 轴)增大逐渐减小,符合
cos(2πx)·exp(-x)的数学特性。 - X 轴标签 :
time [s],采用**kwargs方式设置为大号加粗字体,位于 X 轴底部居中。 - Y 轴标签 :
Damped oscillation [V],采用FontProperties方式设置为Times New Roman 斜体衬线字体,垂直显示在 Y 轴左侧。 - (可选)标题与署名:子图标题、全局总标题、画布底部署名,层级清晰,符合学术图表规范。
五、关键知识点拓展
1. 两种字体样式设置方式对比
表格
| 方式 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
**kwargs直接传参 |
简单样式、临时修改 | 代码简洁、直观 | 样式复用性差,复杂样式代码冗余 |
FontProperties对象 |
复杂样式、多标签复用 | 样式统一、可复用、配置灵活 | 需额外创建对象,代码稍长 |
2. 中文显示问题解决方案
若运行代码出现中文乱码,在代码开头添加以下配置:
python
运行
# 解决中文乱码
plt.rcParams['font.sans-serif'] = ['SimSun', 'Microsoft YaHei']
# 解决负号显示异常
plt.rcParams['axes.unicode_minus'] = False
3. 坐标系统说明
表格
| 坐标系 | 适用 API | 坐标范围 | 特点 |
|---|---|---|---|
| 数据坐标 | ax.text() |
与图表数据范围一致 | 随缩放、平移变化 |
| 子图相对坐标 | ax.text(transform=ax.transAxes) |
0-1(子图左下角为原点) | 固定在子图内,不随数据缩放变化 |
| 画布相对坐标 | plt.figtext() |
0-1(画布左下角为原点) | 固定在画布上,不受子图位置影响 |
4. 常见样式优化技巧
- 调整标签边距 :通过
labelpad(坐标轴标签)、pad(标题)避免标签与轴 / 刻度重叠。 - 旋转标签 :给
xlabel/ylabel添加rotation=45,实现标签斜向显示,适合长文本。 - 添加背景色 :给标题 / 标签添加
backgroundcolor='#f0f0f0',突出文本。 - 多子图总标题 :用
suptitle()统一多子图图表的主题,避免每个子图重复标题。
六、常见使用场景示例
1. 多子图添加总标题
python
运行
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 8))
# 绘制子图...
fig.suptitle('2025 Annual Sales Report', y=0.99, fontsize=16, fontweight='bold')
2. 画布添加水印
python
运行
plt.figtext(0.5, 0.5, 'Confidential', ha='center', va='center',
fontsize=50, color='gray', alpha=0.2, rotation=30)
3. 坐标轴标签斜向显示
python
运行
ax.set_xlabel('Long Label Name', rotation=30, ha='right') # 右对齐避免重叠
annotate 标注全解析(附完整可运行代码)
这组资料系统讲解了 Matplotlib 中最强大的标注工具 annotate(),涵盖两种 API、坐标系、箭头样式、连接样式、实战案例,下面是结构化梳理与深度解读。
一、核心函数定义
annotate() 用于在图表中添加带箭头的文本标注,支持 pyplot 和面向对象(OO)两种调用方式:
- pyplot API :
matplotlib.pyplot.annotate(text, xy, *args, **kwargs) - OO API :
Axes.annotate(self, text, xy, *args, **kwargs)
二、核心参数详解
1. 基础位置参数
表格
| 参数 | 说明 |
|---|---|
text |
标注的文本内容(str) |
xy |
被标注点的坐标,格式为 (float, float),坐标系由 xycoords 决定 |
xytext |
标注文本的坐标,格式为 (float, float),默认与 xy 相同 |
2. 坐标系参数(xycoords / textcoords)
这是 annotate 最核心的特性,支持多种坐标系,灵活控制标注位置:
xycoords(被标注点的坐标系)
表格
| 属性值 | 含义 |
|---|---|
'data' |
默认值,以数据坐标为参考(与图表刻度一致) |
'figure points' |
以绘图区左下角为参考,单位是点数 |
'figure pixels' |
以绘图区左下角为参考,单位是像素数 |
'figure fraction' |
以绘图区左下角为参考,单位是百分比(0-1) |
'axes points' |
以子绘图区左下角为参考,单位是点数 |
'axes pixels' |
以子绘图区左下角为参考,单位是像素数 |
'axes fraction' |
以子绘图区左下角为参考,单位是百分比(0-1) |
'polar' |
使用极坐标系 |
textcoords(标注文本的坐标系)
除支持上述所有值外,额外增加 2 种偏移坐标系:
表格
| 属性值 | 含义 |
|---|---|
'offset points' |
相对于被注释点 xy 的偏移量(单位是点) |
'offset pixels' |
相对于被注释点 xy 的偏移量(单位是像素) |
3. 箭头样式参数(arrowprops)
arrowprops 是字典类型,用于控制箭头的样式、颜色、连接方式等,是 annotate 的灵魂参数。
基础箭头参数(未设置 arrowstyle 时可用)
表格
| 关键字 | 说明 |
|---|---|
width |
箭身的宽度(单位:点) |
headwidth |
箭头头部的宽度(点) |
headlength |
箭头头部的长度(点) |
shrink |
箭头两端收缩的百分比(占总长) |
箭头样式(arrowstyle)
设置 arrowstyle 后,上述基础参数失效,可直接使用预设样式,常用样式如下:
表格
| 箭头样式 | 默认参数 | 效果 |
|---|---|---|
'-' |
None |
无箭头直线 |
'->' |
head_length=0.4, head_width=0.2 |
标准右箭头 |
'<-' |
head_length=0.4, head_width=0.2 |
标准左箭头 |
'<->' |
head_length=0.4, head_width=0.2 |
双向箭头 |
'fancy' |
head_length=0.4, head_width=0.4, tail_width=0.4 |
fancy 箭头 |
'simple' |
head_length=0.5, head_width=0.5, tail_width=0.2 |
简单箭头 |
'wedge' |
tail_width=0.3, shrink_factor=0.5 |
楔形箭头 |
FancyArrowPatch 高级参数
表格
| 关键字 | 说明 |
|---|---|
connectionstyle |
连接线的样式(控制箭头路径的弯曲) |
relpos |
箭头起点相对文本的位置,默认 (0.5, 0.5)(文本中心) |
patchA/patchB |
箭头起点 / 终点绑定的图形对象 |
shrinkA/shrinkB |
箭头起点 / 终点的缩进点数,默认 2 |
mutation_scale |
箭头大小缩放比例,默认文本尺寸 |
4. 连接线样式(connectionstyle)
用于控制箭头从文本到标注点的路径形状,核心样式如下:
表格
| 名称 | 默认参数 | 说明 |
|---|---|---|
angle |
angleA=90, angleB=0, rad=0.0 |
折线连接,可设置两个角度 |
angle3 |
angleA=90, angleB=0 |
二次样条折线(3 个控制点) |
arc |
angleA=0, angleB=0, rad=0.0 |
圆弧连接 |
arc3 |
rad=0.0 |
二次样条圆弧(3 个控制点,最常用) |
bar |
armA=0.0, armB=0.0, fraction=0.3 |
直角折线连接 |
💡
angle3和arc3中的3代表路径由 3 个控制点生成,是平滑的二次曲线。
三、完整实战代码(含多种场景)
1. 基础标注:衰减震荡曲线标注
python
运行
import numpy as np
import matplotlib.pyplot as plt
# 生成衰减震荡数据
x = np.arange(0, 10, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y)
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
# 标注点坐标 (5, 0)
xdata, ydata = 5, 0
# 转换为屏幕像素坐标
xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))
# 文本框样式
bbox = dict(boxstyle="round", fc="0.8")
# 箭头样式:-> 箭头,angle 连接
arrowprops = dict(
arrowstyle = "->",
connectionstyle = "angle,angleA=0,angleB=90,rad=10")
offset = 72
# 数据坐标标注:相对偏移
ax.annotate(
f'data = ({xdata:.1f}, {ydata:.1f})',
(xdata, ydata),
xytext=(-2*offset, offset), textcoords='offset points',
bbox=bbox, arrowprops=arrowprops
)
# 屏幕像素坐标标注
ax.annotate(
f'display = ({xdisplay:.1f}, {ydisplay:.1f})',
xy=(xdisplay, ydisplay), xycoords='figure pixels',
xytext=(0.5*offset, -offset), textcoords='offset points',
bbox=bbox, arrowprops=arrowprops
)
plt.tight_layout()
plt.show()
2. 极坐标标注:螺旋曲线标注
python
运行
import numpy as np
import matplotlib.pyplot as plt
# 创建极坐标子图
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, polar=True)
# 生成螺旋曲线数据
r = np.arange(0, 1, 0.001)
theta = 2 * 2*np.pi * r
line, = ax.plot(theta, r, color='#ee8d18', lw=3)
# 选择索引800的点进行标注
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
# 添加标注
ax.annotate(
'a polar annotation',
xy=(thistheta, thisr), # 极坐标:(角度, 半径)
xytext=(0.05, 0.05), # 文本位置:画布百分比坐标
textcoords='figure fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left',
verticalalignment='bottom'
)
plt.tight_layout()
plt.show()
3. 箭头样式与连接样式演示
python
运行
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# 定义演示函数
def demo_con_style(ax, connectionstyle):
x1, y1 = 0.3, 0.2
x2, y2 = 0.8, 0.6
ax.plot([x1, x2], [y1, y2], ".")
ax.annotate(
"",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(
arrowstyle="->", color="0.5",
shrinkA=5, shrinkB=5,
patchA=None, patchB=None,
connectionstyle=connectionstyle,
),
)
ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
transform=ax.transAxes, ha="left", va="top")
# 创建3行5列子图
fig, axs = plt.subplots(3, 5, figsize=(8, 4.8))
# 演示不同连接样式
demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
demo_con_style(axs[0, 1], "arc3,rad=0.")
demo_con_style(axs[1, 1], "arc3,rad=0.3")
demo_con_style(axs[2, 1], "arc3,rad=-0.3")
demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[0, 4], "bar,fraction=0.3")
demo_con_style(axs[1, 4], "bar,fraction=-0.3")
demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")
# 统一设置子图
for ax in axs.flat:
ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
fig.tight_layout(pad=0.2)
plt.show()
四、运行效果解读
1. 基础标注效果
- 标注点
(5, 0)处添加了两个标注:- 数据坐标标注:基于图表刻度,相对偏移定位,带圆角文本框和箭头。
- 屏幕像素标注:基于画布像素,固定位置,不受图表缩放影响。
- 箭头采用
angle连接样式,实现直角转折,清晰指向标注点。
2. 极坐标标注效果
- 螺旋曲线的指定点(索引 800)添加标注,文本固定在画布左下角(5% 位置)。
- 箭头自动适配极坐标系,准确指向目标点,两端缩进 5% 避免遮挡。
3. 连接样式效果
- 15 种不同的连接样式,直观展示了
angle/angle3/arc/arc3/bar等样式的差异。 - 可通过调整
rad(弧度)、angleA/angleB(角度)等参数,自定义箭头路径的弯曲程度。
五、关键知识点拓展
1. 坐标系选择指南
表格
| 场景 | 推荐坐标系 | 说明 |
|---|---|---|
| 标注数据点 | 'data' |
与数据刻度绑定,缩放图表时标注自动跟随 |
| 固定位置标注 | 'figure fraction' |
基于画布百分比,不受子图位置、缩放影响 |
| 相对偏移标注 | 'offset points' |
相对于标注点偏移,适合批量标注 |
| 极坐标标注 | 'polar' |
自动适配极坐标系统 |
2. 箭头样式最佳实践
- 学术图表 :推荐
arrowstyle='->'+connectionstyle='arc3,rad=0.2',简洁清晰。 - 复杂标注 :使用
arrowstyle='fancy',搭配mutation_scale调整大小,突出重点。 - 避免遮挡 :设置
shrinkA/shrinkB让箭头两端缩进,不遮挡文本和数据点。
3. 中文显示问题
若标注出现中文乱码,在代码开头添加:
python
运行
plt.rcParams['font.sans-serif'] = ['SimSun', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
4. 标注裁剪控制
annotation_clip 参数控制标注是否裁剪:
True:仅当标注点在子图内时显示标注(默认,xycoords='data'时生效)。False:无论标注点位置,始终显示标注。