一、Figure 和 Axes 上的文本
Matplotlib 提供了丰富的文本支持,包括数学表达式、TrueType 字体、旋转文本、换行符以及 Unicode 字符等。
1. 文本 API 示例
通过 pyplot API
和面向对象的 OO API
,我们可以在图形的不同位置添加文本。
方法 | pyPLot API | OO API | 描述 |
---|---|---|---|
text | text | text | 在子图的任意位置添加文本 |
annotate | annotate | annotate | 添加带箭头的注解 |
xlabel | xlabel | set_xlabel | 为子图添加 x 轴标签 |
ylabel | ylabel | set_ylabel | 为子图添加 y 轴标签 |
title | title | set_title | 为子图添加标题 |
figtext | text | text | 在画布上添加文本 |
suptitle | suptitle | suptitle | 为画布添加标题 |
2. 子图上的文本
- text 方法:用于在子图的特定坐标
(x, y)
位置插入文本,支持bbox
、style
、color
等样式设置。 - 示例:
ax.text(3, 8, 'boxed italics text in data coords', style='italic', bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
3. 设置 x 和 y 轴标签
- set_xlabel 和 set_ylabel 方法用于添加 x 和 y 轴标签,支持
fontdict
和**kwargs
来设置字体样式。 - labelpad 控制标签与坐标轴之间的距离,
loc
控制标签位置。
4. 标题(title 和 suptitle)
- set_title 设置子图标题,支持
pad
和y
参数来调整标题位置。 - suptitle 为整个图形添加一个标题,支持
y
参数来控制位置。
5. 注解(annotate)
- annotate 方法可在图中添加带箭头的注解,
xy
指向位置,xytext
设置注解文本的位置,arrowprops
设置箭头样式。
二、Tick 上的文本
Tick(刻度)和 Ticklabel(刻度标签)可以通过 set_ticks
和 set_ticklabels
方法进行手动设置。
1. 简单模式
- set_ticks:手动设置刻度的位置。
- set_ticklabels:手动设置刻度标签内容。
示例:
axs[1].xaxis.set_ticks([0, 1, 2, 3, 4, 5, 6])
axs[1].xaxis.set_ticklabels(['zero', 'one', 'two', 'three', 'four', 'five', 'six'], rotation=30, fontsize='small')
2. Tick Locators 和 Formatters
- Locators 用于设置刻度位置,如
MaxNLocator
、AutoLocator
、MultipleLocator
等。 - Formatters 用于设置刻度标签格式,如
FormatStrFormatter
、FuncFormatter
等。
示例:
from matplotlib.ticker import MaxNLocator
axs[0].xaxis.set_major_locator(MaxNLocator(nbins=7))
三、图例(legend)
Matplotlib 提供了两种方式来绘制图例:pyplot 和面向对象(OO)方法。通过 legend
方法可以为图形添加图例。
1. 图例位置
loc
参数控制图例的显示位置,可选择位置字符串(如 'upper right'
)或对应的数字代码。
示例:
ax.legend(loc='upper right') # 或者 ax.legend(loc=1)
2. 设置图例边框和背景
- frameon:是否显示边框。
- edgecolor:设置边框颜色。
- facecolor:设置背景颜色。
示例:
ax.legend(frameon=False) # 去掉图例边框
ax.legend(edgecolor='blue') # 设置图例边框颜色
ax.legend(facecolor='gray') # 设置图例背景颜色
3. 设置图例标题
可以使用 title
参数为图例设置标题。
示例:
ax.legend(title='Legend Title')
四、字体属性设置
Matplotlib 提供了全局字体设置和局部字体设置两种方式。
- 全局字体设置:通过
plt.rcParams
修改全局字体。 - 局部字体设置:使用
fontproperties
参数进行单独的字体调整。
全局字体设置示例:
plt.rcParams['font.sans-serif'] = ['SimSun'] # 设置默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
局部字体设置示例:
plt.xlabel('x 轴名称', fontproperties='Microsoft YaHei', fontsize=16)
plt.ylabel('y 轴名称', fontproperties='Microsoft YaHei', fontsize=14)