文本属性与布局#

使用 Matplotlib 控制文本及其布局的属性。

matplotlib.text.Text 实例具有多种属性,可以通过关键字参数传递给 set_title、set_xlabel、text 等进行配置。

属性

值类型

alpha

浮点数

backgroundcolor

任意 Matplotlib 颜色

bbox

Rectangle 属性字典,加上键 'pad'(以点数为单位的内边距)

clip_box

matplotlib.transform.Bbox 实例

clip_on

布尔值

clip_path

一个 Path 实例和一个 Transform 实例,或者是 Patch

color

任意 Matplotlib 颜色

family(字体族)

[ 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ]

fontproperties(字体属性)

FontProperties(字体属性对象)

horizontalalignment 或 ha(水平对齐)

[ 'center' | 'right' | 'left' ]

label

任意字符串

linespacing

浮点数

multialignment(多行对齐)

['left' | 'right' | 'center' ]

name 或 fontname(字体名称)

字符串,例如:['Sans' | 'Courier' | 'Helvetica' ...]

picker

[None|float|bool|callable]

position

(x, y)

rotation

[ 角度(度) | 'vertical' | 'horizontal' ]

size 或 fontsize(字号)

[ 以点数为单位的字号 | 相对字号,例如:'small', 'x-large' ]

style 或 fontstyle(字体样式)

[ 'normal' | 'italic' | 'oblique' ]

text

字符串或任何可通过 '%s' 转换输出的内容

transform

Transform 子类

variant(变体)

[ 'normal' | 'small-caps' ]

verticalalignment 或 va(垂直对齐)

[ 'center' | 'top' | 'bottom' | 'baseline' ]

visible

布尔值

weight 或 fontweight(字重)

[ 'normal' | 'bold' | 'heavy' | 'light' | 'ultrabold' | 'ultralight']

x

浮点数

y

浮点数

zorder

任意数字

文本对齐#

您可以使用对齐参数 horizontalalignment、verticalalignment 和 multialignment 来布局文本。horizontalalignment 控制文本的 x 位置参数是指文本边界框的左侧、中心还是右侧。verticalalignment 控制文本的 y 位置参数是指文本边界框的底部、中心还是顶部。multialignment 仅适用于换行分隔的字符串,用于控制多行文本是左对齐、居中对齐还是右对齐。下面是一个使用 text() 命令展示各种对齐可能性的示例。代码中全程使用 transform=ax.transAxes,表示坐标是相对于坐标轴(Axes)边界框给出的,其中 (0, 0) 是坐标轴的左下角,(1, 1) 是右上角。

import matplotlib.pyplot as plt

import matplotlib.patches as patches

# build a rectangle in axes coords
left, width = 0.25, 0.5
bottom, height = 0.25, 0.5
right = left + width
top = bottom + height

fig = plt.figure()
ax = fig.add_axes((0, 0, 1, 1))

# axes coordinates: (0, 0) is bottom left and (1, 1) is upper right
p = patches.Rectangle(
    (left, bottom), width, height,
    fill=False, transform=ax.transAxes, clip_on=False
    )

ax.add_patch(p)

ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5*(bottom+top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5*(bottom+top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=20, color='red',
        transform=ax.transAxes)

ax.text(right, 0.5*(bottom+top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

ax.set_axis_off()
plt.show()
text props

相对字号#

字号既可以以点数指定,也可以作为相对于默认字号的字符串指定。以下是相对字号的有效值:

相对字号

默认字号的缩放比例

xx-small

0.579

x-small

0.694

small

0.833

medium

1.000

large

1.200

x-large

1.440

xx-large

1.728

默认字体#

基础默认字体由一组 rcParams 控制。要设置数学表达式的字体,请使用以 mathtext 开头的 rcParams(请参阅 mathtext)。

rcParam

用法

'font.family'

字体族列表(需安装在用户机器上)和/或 {'cursive', 'fantasy', 'monospace', 'sans', 'sans serif', 'sans-serif', 'serif'}。

'font.style'

默认样式,例如 'normal', 'italic'。

'font.variant'

默认变体,例如 'normal', 'small-caps' (未测试)

'font.stretch'

默认拉伸,例如 'normal', 'condensed' (不完整)

'font.weight'

默认字重,可以是字符串或整数。

'font.size'

以点数为单位的默认字号。相对字号(如 'large', 'x-small')是根据此字号计算的。

Matplotlib 可以使用用户计算机上安装的字体族,例如 Helvetica、Times 等。字体族也可以使用通用族别名来指定,如 ({'cursive', 'fantasy', 'monospace', 'sans', 'sans serif', 'sans-serif', 'serif'})。

注意

要获取可用字体的完整列表

matplotlib.font_manager.get_font_names()

通用族别名与实际字体族之间的映射关系(在 默认 rcParams 中提到)由以下 rcParams 控制:

基于 CSS 的通用族别名

带有映射关系的 rcParam

'serif'

'font.serif'

'monospace'

'font.monospace'

'fantasy'

'font.fantasy'

'cursive'

'font.cursive'

{'sans', 'sans serif', 'sans-serif'}

'font.sans-serif'

如果 'font.family' 中出现了任何通用族名称,我们会将其替换为相应 rcParam 映射中的所有条目。例如:

matplotlib.rcParams['font.family'] = ['Family1', 'serif', 'Family2']
matplotlib.rcParams['font.serif'] = ['SerifFamily1', 'SerifFamily2']

# This is effectively translated to:
matplotlib.rcParams['font.family'] = ['Family1', 'SerifFamily1', 'SerifFamily2', 'Family2']

带有非拉丁字符的文本#

从 v2.0 开始,默认字体 DejaVu 包含了许多西方字母的字形,但不包括中文、韩文或日文等其他文字系统。

要将默认字体设置为支持您所需代码点的字体,请将字体名称添加到 'font.family'(推荐),或者添加到所需的别名列表中。

# first method
matplotlib.rcParams['font.family'] = ['Source Han Sans TW', 'sans-serif']

# second method
matplotlib.rcParams['font.family'] = ['sans-serif']
matplotlib.rcParams['sans-serif'] = ['Source Han Sans TW', ...]

通用族别名列表包含的字体要么随 Matplotlib 一起提供(因此被找到的几率为 100%),要么是在大多数系统中极有可能存在的字体。

设置自定义字体族时,一个好的做法是在字体列表末尾添加一个通用字体族作为最后的兜底选择。

您也可以在 .matplotlibrc 文件中进行设置:

font.family: Source Han Sans TW, Arial, sans-serif

要基于每个 Artist(绘图对象)控制字体,请使用 文本属性与布局 中记录的 name、fontname 或 fontproperties 关键字参数。

在 Linux 上,fc-list 是一个发现字体名称的实用工具;例如:

$ fc-list :lang=zh family
Noto to Sans Mono CJK TC,Noto Sans Mono CJK TC Bold
Noto Sans CJK TC,Noto Sans CJK TC Medium
Noto Sans CJK TC,Noto Sans CJK TC DemiLight
Noto Sans CJK KR,Noto Sans CJK KR Black
Noto Sans CJK TC,Noto Sans CJK TC Black
Noto Sans Mono CJK TC,Noto Sans Mono CJK TC Regular
Noto Sans CJK SC,Noto Sans CJK SC Light

列出所有支持中文的字体。

由 Sphinx-Gallery 生成的画廊