Matplotlib Fig 级文本与标注函数
除 text() 和 annotate() 外,Matplotlib 还提供了 Figure 级别的文本函数、表格添加和箭头绘制。
函数一览
| 函数 | 功能 |
|---|---|
| figtext() | 在 Figure 级别(非 Axes)添加文本 |
| figlegend() | 在 Figure 级别添加图例(跨 Axes) |
| table() | 在 Axes 中添加表格 |
| arrow() | 添加简单箭头 |
figtext() - Figure 级文本
matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)
与 text() 类似,但坐标系统为 Figure 坐标(0-1),而非数据坐标。
实例
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([0, 1], [0, 1], 'steelblue')
ax.set_title('Axes-level (text vs figtext)')
# Axes 级文本(数据坐标)
ax.text(0.3, 0.7, 'Axes text (data coords)',
fontsize=12, color='blue')
# Figure 级文本(Figure 相对坐标 0-1)
plt.figtext(0.5, 0.02,
'Figure text at bottom center (Figure coords)',
ha='center', fontsize=10, color='gray')
plt.figtext(0.02, 0.95,
'Top left',
ha='left', va='top',
fontsize=12, fontweight='bold', color='red')
plt.show()
import numpy as np
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([0, 1], [0, 1], 'steelblue')
ax.set_title('Axes-level (text vs figtext)')
# Axes 级文本(数据坐标)
ax.text(0.3, 0.7, 'Axes text (data coords)',
fontsize=12, color='blue')
# Figure 级文本(Figure 相对坐标 0-1)
plt.figtext(0.5, 0.02,
'Figure text at bottom center (Figure coords)',
ha='center', fontsize=10, color='gray')
plt.figtext(0.02, 0.95,
'Top left',
ha='left', va='top',
fontsize=12, fontweight='bold', color='red')
plt.show()
figlegend() - Figure 级图例
matplotlib.pyplot.figlegend(*args, **kwargs)
当多个 Axes 需要共享图例时,figlegend() 可在 Figure 级别放置图例。
实例
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')
# 每个 Axes 绘制相同的两条曲线,但不各自添加图例
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax1.plot(x, np.cos(x), 'r--', label='cos(x)')
ax1.set_title('Plot 1')
ax2.plot(x, np.sin(x), 'b-', label='sin(x)')
ax2.plot(x, np.cos(x), 'r--', label='cos(x)')
ax2.set_title('Plot 2')
# Figure 级图例(放在 Figure 外侧顶部)
fig.legend(loc='outside upper center', ncol=2,
fontsize=11, frameon=True)
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# 每个 Axes 绘制相同的两条曲线,但不各自添加图例
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax1.plot(x, np.cos(x), 'r--', label='cos(x)')
ax1.set_title('Plot 1')
ax2.plot(x, np.sin(x), 'b-', label='sin(x)')
ax2.plot(x, np.cos(x), 'r--', label='cos(x)')
ax2.set_title('Plot 2')
# Figure 级图例(放在 Figure 外侧顶部)
fig.legend(loc='outside upper center', ncol=2,
fontsize=11, frameon=True)
plt.show()
table() - 在 Axes 中添加表格
matplotlib.pyplot.table(cellText=None, cellColours=None,
cellLoc='right', colWidths=None, rowLabels=None,
rowColours=None, rowLoc='left', colLabels=None,
colColours=None, colLoc='center', loc='bottom',
bbox=None, edges='closed', **kwargs)
实例
import matplotlib.pyplot as plt
import numpy as np
# 要显示的数据
data = [[85, 90, 78, 92],
[76, 88, 82, 85],
[90, 93, 88, 95]]
row_labels = ['Student A', 'Student B', 'Student C']
col_labels = ['Math', 'English', 'Science', 'History']
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# 绘制对比图
x = np.arange(len(col_labels))
for i, (row, label) in enumerate(zip(data, row_labels)):
ax.plot(x, row, 'o-', label=label, markersize=8)
ax.set_xticks(x)
ax.set_xticklabels(col_labels)
ax.set_title('Student Scores')
ax.legend()
ax.grid(True, alpha=0.3)
# 在图表下方添加表格
table = ax.table(cellText=data,
rowLabels=row_labels,
colLabels=col_labels,
cellLoc='center',
loc='bottom',
bbox=[0, -0.35, 1, 0.25]) # [left, bottom, width, height]
plt.show()
import numpy as np
# 要显示的数据
data = [[85, 90, 78, 92],
[76, 88, 82, 85],
[90, 93, 88, 95]]
row_labels = ['Student A', 'Student B', 'Student C']
col_labels = ['Math', 'English', 'Science', 'History']
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# 绘制对比图
x = np.arange(len(col_labels))
for i, (row, label) in enumerate(zip(data, row_labels)):
ax.plot(x, row, 'o-', label=label, markersize=8)
ax.set_xticks(x)
ax.set_xticklabels(col_labels)
ax.set_title('Student Scores')
ax.legend()
ax.grid(True, alpha=0.3)
# 在图表下方添加表格
table = ax.table(cellText=data,
rowLabels=row_labels,
colLabels=col_labels,
cellLoc='center',
loc='bottom',
bbox=[0, -0.35, 1, 0.25]) # [left, bottom, width, height]
plt.show()
arrow() - 添加箭头
matplotlib.pyplot.arrow(x, y, dx, dy, **kwargs)
arrow() 是添加简单箭头的快捷方式。对于复杂箭头标注,推荐使用 annotate()。
实例
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
# 绘制坐标系
ax.spines[['left', 'bottom']].set_position(('data', 0))
ax.spines[['top', 'right']].set_visible(False)
ax.set_xlim(-1, 5)
ax.set_ylim(-1, 5)
# 各种箭头
ax.arrow(0, 0, 3, 0, head_width=0.2, head_length=0.2,
fc='red', ec='red', label='Right 3 units')
ax.arrow(0, 0, 0, 3, head_width=0.2, head_length=0.2,
fc='blue', ec='blue', label='Up 3 units')
ax.arrow(0, 0, 2, 2, head_width=0.2, head_length=0.2,
fc='green', ec='green', label='Diagonal')
ax.set_title('arrow() - Simple Arrows')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
import numpy as np
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
# 绘制坐标系
ax.spines[['left', 'bottom']].set_position(('data', 0))
ax.spines[['top', 'right']].set_visible(False)
ax.set_xlim(-1, 5)
ax.set_ylim(-1, 5)
# 各种箭头
ax.arrow(0, 0, 3, 0, head_width=0.2, head_length=0.2,
fc='red', ec='red', label='Right 3 units')
ax.arrow(0, 0, 0, 3, head_width=0.2, head_length=0.2,
fc='blue', ec='blue', label='Up 3 units')
ax.arrow(0, 0, 2, 2, head_width=0.2, head_length=0.2,
fc='green', ec='green', label='Diagonal')
ax.set_title('arrow() - Simple Arrows')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Matplotlib 参考文档