Skip to content

Files

Latest commit

Jan 9, 2017
86a95ed · Jan 9, 2017

History

History
660 lines (489 loc) · 52.2 KB

3.4.md

File metadata and controls

660 lines (489 loc) · 52.2 KB

3.4 文本处理

原文:Working with text

译者:飞龙

协议:CC BY-NC-SA 4.0

引言

matplotlib 具有优秀的文本支持,包括数学表达式,光栅和向量输出的 truetype 支持,任意旋转的换行分隔文本和 unicode 支持。 因为我们直接在输出文档中嵌入字体,例如 postscript 或 PDF,你在屏幕上看到的也是你在打印件中得到的。 freetype2 可产生非常漂亮,抗锯齿的字体,即使在小光栅尺寸下看起来也不错。 matplotlib 拥有自己的matplotlib.font_manager,感谢 Paul Barrett,他实现了一个跨平台,符合 W3C 标准的字体查找算法。

你可以完全控制每个文本属性(字体大小,字体重量,文本位置和颜色等),并在rc文件中设置合理的默认值。 并且对于那些对数学或科学图像感兴趣的人,matplotlib 实现了大量的 TeX 数学符号和命令,来支持你图中任何地方放置数学表达式。

基本的文本命令

text

Axes的任意位置添加文本。

命令式:matplotlib.pyplot.text,面向对象:matplotlib.axes.Axes.text

xlabel

向 x 轴添加轴标签。

命令式:matplotlib.pyplot.xlabel,面向对象:matplotlib.axes.Axes.set_xlabel

ylabel

向 y 轴添加轴标签。

命令式:matplotlib.pyplot.ylabel,面向对象:matplotlib.axes.Axes.set_ylabel

title

Axes添加标题。

命令式:matplotlib.pyplot.title,面向对象:matplotlib.axes.Axes.set_title

figtext

Figure的任意位置添加文本。

命令式:matplotlib.pyplot.figtext,面向对象:matplotlib.figure.Figure.text

suptitle

Figure添加标题。

命令式:matplotlib.pyplot.suptitle,面向对象:matplotlib.figure.Figure.suptitle

annotate

Axes添加标注,带有可选的箭头。

命令式:matplotlib.pyplot.annotate,面向对象:matplotlib.axes.Axes.annotate

所有这些函数创建并返回一个matplotlib.text.Text()实例,它可以配置各种字体和其他属性。 下面的示例在实战中展示所有这些命令。

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

fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')

ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('axes title')

ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})

ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)

ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik')

ax.text(0.95, 0.01, 'colored text in axes coords',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)


ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.axis([0, 10, 0, 10])

plt.show()

文本属性及布局

matplotlib.text.Text实例有各种属性,可以通过关键字参数配置文本命令(例如,title()xlabel()text())。

属性 值类型
alpha 浮点
backgroundcolor 任何 matplotlib 颜色
bbox rectangle prop dict plus key 'pad' which is a pad in points
clip_box matplotlib.transform.Bbox 实例
clip_on [True / False]
clip_path Path 实例和 Transform 实例,Patch
color 任何 matplotlib 颜色
family [ 'serif' / 'sans-serif' / 'cursive' / 'fantasy' / 'monospace' ]
fontproperties matplotlib.font_manager.FontProperties 实例
horizontalalignment or ha [ 'center' / 'right' / 'left' ]
label 任何字符串
linespacing 浮点
multialignment ['left' / 'right' / 'center' ]
name or fontname 字符串,例如 ['Sans' / 'Courier' / 'Helvetica' ...]
picker [None / 浮点 / 布尔值 / 可调用对象]`
position (x,y)
rotation [ 角度制的角度 / 'vertical' / 'horizontal'
size or fontsize [ 点的尺寸
style or fontstyle [ 'normal' / 'italic' / 'oblique']
text 字符串或任何可使用'%s'打印的东西
transform matplotlib.transform 实例
variant [ 'normal' / 'small-caps' ]
verticalalignment or va [ 'center' / 'top' / 'bottom' / 'baseline' ]
visible [True / False]
weight or fontweight [ 'normal' / 'bold' / 'heavy' / 'light' / 'ultrabold' / 'ultralight']
x 浮点
y 浮点
zorder 任意数值

你可以使用对齐参数horizontalalignmentverticalalignmentmultialignment来布置文本。 horizontalalignment控制文本的x位置参数表示文本边界框的左边,中间或右边。 verticalalignment控制文本的y位置参数表示文本边界框的底部,中心或顶部。 multialignment,仅对于换行符分隔的字符串,控制不同的行是左,中还是右对齐。 这里是一个使用text()命令显示各种对齐方式的例子。 在整个代码中使用transform = ax.transAxes,表示坐标相对于轴边界框给出,其中0,0是轴的左下角,1,1是右上角。

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height

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

# axes coordinates are 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()

编写数学表达式

你可以在任何 matplotlib 文本字符串中使用子 TeX 标记,将它放在一对美元符号($)内。

注意,你不需要安装 TeX,因为 matplotlib 提供了自己的 TeX 表达式解析器,布局引擎和字体。 布局引擎是 Donald Knuth 的 TeX 中的布局算法的一种相当直接的适配版,所以质量是相当不错的(matplotlib 还为那些想要调用 TeX 生成文本的人提供一个usetex选项(参见使用 LaTeX 渲染文本 )。

任何文本元素都可以使用数学文本。 你应该使用原始字符串(在引号前面加一个'r'),并用美元符号($)包围数学文本,如 TeX。 常规文本和数学文本可以在同一个字符串内交错。 Mathtext 可以使用 Computer Modern 字体(来自 (La)TeX),STIX 字体(为与 Times 混合使用而设计)或你提供的 Unicode 字体。 可以使用自定义变量mathtext.fontset选择 mathtext 字体(请参阅自定义 matplotlib

注意

在Python的 『narrow』 构建中,如果使用 STIX 字体,你还应该将ps.fonttypepdf.fonttype设置为 3(默认值),而不是 42。否则一些字符将不可见。

下面是个简单的例子:

# plain text
plt.title('alpha > beta')

生成alpha > beta

但是这个:

# math text
plt.title(r'$\alpha > \beta$')

生成

注意

Mathtext 应该放在一对美元符号($)之间。 为了易于显示货币值,例如$ 100.00,如果整个字符串中存在单个美元符号,则它将被逐字显示为美元符号。 这是常规 TeX 的一个小改变,其中非数学文本中的美元符号必须被转义('$')。

注意

虽然一对美元符号($)内的语法是 TeX 风格的,但是外面的文本不是。 特别是,字符:

# $ % & ~ _ ^ \ { } \( \) \[ \]

在 TeX 中的数学模式之外有特殊的意义。 因此,根据rcParam text.usetex标志这些字符的表现有所不同。 更多信息请参阅usetex教程

下标和上标

为了制作下标和上标,使用_或者^符号:

r'$\alpha_i > \beta_i$'

一些符号会自动将它们的下标或上标放在操作符的底部或顶部,例如,为了编写 0 到无穷的 的和,你可以:

r'$\sum_{i=0}^\infty x_i$'

分数、二项式和堆叠数

可以使用\frac{}{}\binomial{}{}\stackrel{}{}命令分别创建分数,二项式和堆叠数字:

r'$\frac{3}{4} \binom{3}{4} \stackrel{3}{4}$'

产生

分数可以任意嵌套:

r'$\frac{5 - \frac{1}{x}}{4}$'

产生

请注意,在分数周围放置圆括号和花括号需要特别注意。 这种明显的方式会产生太小的括号:

r'$(\frac{5 - \frac{1}{x}}{4})$'

解决方案是在括号前面加上\left\right以通知解析器这些括号包含整个对象:

r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'

根式

根式可以有\sqrt[]{}产生,例如:

r'$\sqrt{2}$'

方括号内可以(可选地)设置任何底数。 请注意,底数必须是一个简单的表达式,并且不能包含布局命令,如分数或上下标:

r'$\sqrt[3]{x}$'

字体

用于数学符号的默认字体是斜体。

注意

此默认值可以使用mathtext.default rcParam更改。 这是非常有用的,例如,通过将其设置为regular,使用与常规非数学文本相同的字体作为数学文本。

为了修改字体,例如,以 Roman 字体编写sin,使用字体命令来闭合文本:

r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$'

这里st是斜体(默认)的变量,sin是罗马字体,振幅A是书法字体。 注意在上面的例子中,Asin之间的间距被挤压。 你可以使用间距命令在它们之间添加一些空格:

s(t) = \mathcal{A}\/\sin(2 \omega t)

所有字体的可用选项为:

命令 结果
\mathrm{Roman}
\mathit{Italic}
\mathtt{Typewriter}
\mathcal{CALLIGRAPHY}

使用 STIX 字体时,你也可以选择:

命令 结果
\mathbb{blackboard}
\mathrm{\mathbb{blackboard}}
\mathfrak{Fraktur}
\mathsf{sansserif}
\mathrm{\mathsf{sansserif}}
\mathcircled{circled}

还有三个全局『字体集』可供选择,它们使用matplotlibrc中的mathtext.fontset参数进行选择。

cm: Computer Modern (TeX)

stix: STIX (为和 Times 混合使用而设计)

stixsans: STIX sans-serif

此外,你可以使用\mathdefault{...}或其别名\mathregular{...}来使用用于 mathtext 之外的常规文本的字体。 这种方法有一些限制,最明显的是,可以使用很少的符号,但可用于将数学表达式与图中的其他文本混合。

自定义字体

mathtext 还提供了一种对数学公式使用自定义字体的方法。 这种方法使用起来相当棘手,应该看做为有耐心的用户准备的试验特性。 通过将rcParam mathtext.fontset设置为custom,你可以设置以下参数,这些参数控制用于特定数学字符集的字体文件。

参数 相当于
mathtext.it \mathit{} 默认斜体
mathtext.rm \mathrm{} Roman (upright)
mathtext.tt \mathtt{} 打字机(monospace)
mathtext.bf \mathbf{} 粗体
mathtext.cal \mathcal{} 书法
mathtext.sf \mathsf{} sans-serif

每个参数应该设置为fontconfig字体描述符(在尚未编写的字体章节中定义)。

所使用的字体应该具有 Unicode 映射,以便找到任何非拉丁字符,例如希腊语。 如果要使用未包含在自定义字体中的数学符号,可以将rcParam mathtext.fallback_to_cm设置为True,这将导致自定义字体中找不到特定字符时,数学文本系统使用默认的 Computer Modern 字体中的字符。

请注意,Unicode 中规定的数学字形随时间而演进,许多字体的字形对于 mathtext 可能不在正确位置。

重音符号

重音命令可以位于任何符号之前,在其上添加重音。 他们中的一些些拥有较长和较短的形式。

命令 结果
\acute a\'a
\bar a
\breve a
\ddot a\"a
\dot a\.a
\grave a\a`
\hat a\^a
\tilde a\~a
\vec a
\overline{abc}

另外有两个特殊的重音符号,可以自动调整为符号的宽度:

命令 结果
\widehat{xyz}
\widetilde{xyz}

当把重音放在小写的ij上时应该小心。 注意下面的\imath用来避免i上额外的点:

r"$\hat i\ \ \hat \imath$"

符号

你也可以使用更大量的 TeX 符号,比如\infty\leftarrow\sum\int

小写希腊字母
\alpha \beta \chi
\epsilon \eta \gamma
\lambda \mu \nu
\pi \psi \rho
\theta \upsilon \varepsilon
\varpi \varrho \varsigma
\zeta
大写希腊字母
\Delta \Gamma \Lambda
\Psi \Sigma \Theta
\nabla
希伯来文
\aleph \beth \daleth
分隔符
/ [ \Downarrow
\downarrow \langle \lceil
\rangle \rceil \rfloor
\vert \{ |
大型符号
\bigcap \bigcup \bigodot
\biguplus \bigvee \bigwedge
\oint \prod \sum
标准函数名称
\Pr \arccos \arcsin
\arg \cos \cosh
\coth \csc \deg
\dim \exp \gcd
\inf \ker \lg
\liminf \limsup \ln
\max \min \sec
\sinh \sup \tan
二元运算符和关系符号
\Bumpeq \Cap \Cup
\Doteq \Join \Subset
\Supset \Vdash \Vvdash
\approx \approxeq \ast
\asymp \backepsilon \backsim
\backsimeq \barwedge \because
\between \bigcirc \bigtriangledown
\bigtriangleup \blacktriangleleft \blacktriangleright
\bot \bowtie \boxdot
\boxminus \boxplus \boxtimes
\bullet \bumpeq \cap
\cdot \circ \circeq
\coloneq \cong \cup
\curlyeqprec \curlyeqsucc \curlyvee
\curlywedge \dag \dashv
\ddag \diamond \div
\divideontimes \doteq \doteqdot
\dotplus \doublebarwedge \eqcirc
\eqcolon \eqsim \eqslantgtr
\eqslantless \equiv \fallingdotseq
\frown \geq \geqq
\geqslant \gg \ggg
\gnapprox \gneqq \gnsim
\gtrapprox \gtrdot \gtreqless
\gtreqqless \gtrless \gtrsim
\in \intercal \leftthreetimes
\leq \leqq \leqslant
\lessapprox \lessdot \lesseqgtr
\lesseqqgtr \lessgtr \lesssim
\ll \lll \lnapprox
\lneqq \lnsim \ltimes
\mid \models \mp
\nVDash \nVdash \napprox
\ncong \ne \neq
\neq \nequiv \ngeq
\ngtr \ni \nleq
\nless \nmid \notin
\nparallel \nprec \nsim
\nsubset \nsubseteq \nsucc
\nsupset \nsupseteq \ntriangleleft
\ntrianglelefteq \ntriangleright \ntrianglerighteq
\nvDash \nvdash \odot
\ominus \oplus \oslash
\otimes \parallel \perp
\pitchfork \pm \prec
\precapprox \preccurlyeq \preceq
\precnapprox \precnsim \precsim
\propto \rightthreetimes \risingdotseq
\rtimes \sim \simeq
\slash \smile \sqcap
\sqcup \sqsubset \sqsubset
\sqsubseteq \sqsupset \sqsupset
\sqsupseteq \star \subset
\subseteq \subseteqq \subsetneq
\subsetneqq \succ \succapprox
\succcurlyeq \succeq \succnapprox
\succnsim \succsim \supset
\supseteq \supseteqq \supsetneq
\supsetneqq \therefore \times
\top \triangleleft \trianglelefteq
\triangleq \triangleright \trianglerighteq
\uplus \vDash \varpropto
\vartriangleleft \vartriangleright \vdash
\vee \veebar \wedge
\wr
箭头符号
\Downarrow \Leftarrow
\Leftrightarrow \Lleftarrow
\Longleftarrow \Longleftrightarrow
\Longrightarrow \Lsh
\Nearrow \Nwarrow
\Rightarrow \Rrightarrow
\Rsh \Searrow
\Swarrow \Uparrow
\Updownarrow \circlearrowleft
\circlearrowright \curvearrowleft
\curvearrowright \dashleftarrow
\dashrightarrow \downarrow
\downdownarrows \downharpoonleft
\downharpoonright \hookleftarrow
\hookrightarrow \leadsto
\leftarrow \leftarrowtail
\leftharpoondown \leftharpoonup
\leftleftarrows \leftrightarrow
\leftrightarrows \leftrightharpoons
\leftrightsquigarrow \leftsquigarrow
\longleftarrow \longleftrightarrow
\longmapsto \longrightarrow
\looparrowleft \looparrowright
\mapsto \multimap
\nLeftarrow \nLeftrightarrow
\nRightarrow \nearrow
\nleftarrow \nleftrightarrow
\nrightarrow \nwarrow
\rightarrow \rightarrowtail
\rightharpoondown \rightharpoonup
\rightleftarrows \rightleftarrows
\rightleftharpoons \rightleftharpoons
\rightrightarrows \rightrightarrows
\rightsquigarrow \searrow
\swarrow \to
\twoheadleftarrow \twoheadrightarrow
\uparrow \updownarrow
\updownarrow \upharpoonleft
\upharpoonright \upuparrows
杂项符号
\$ \AA \Finv
\Game \Im \P
\Re \S \angle
\backprime \bigstar \blacksquare
\blacktriangle \blacktriangledown \cdots
\checkmark \circledR \circledS
\clubsuit \complement \copyright
\ddots \diamondsuit \ell
\emptyset \eth \exists
\flat \forall \hbar
\heartsuit \hslash \iiint
\iint \iint \imath
\infty \jmath \ldots
\measuredangle \natural \neg
\nexists \oiiint \partial
\prime \sharp \spadesuit
\sphericalangle \ss \triangledown
\varnothing \vartriangle \vdots
\wp \yen

如果特定符号没有名称(对于 STIX 字体中的许多较为模糊的符号也是如此),也可以使用 Unicode 字符:

ur'$\u23ce$'

示例

下面是个示例,在上下文中展示了许多这些特性。

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()