提交 8eabd8e2 编写于 作者: W wizardforcel

3.4.

上级 02c29557
# 3.4 文本处理
> 原文:[Working with text](http://matplotlib.org/users/index_text.html)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/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`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text),面向对象:[`matplotlib.axes.Axes.text`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.text)
### xlabel
向 x 轴添加轴标签。
命令式:[`matplotlib.pyplot.xlabel`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlabel),面向对象:[`matplotlib.axes.Axes.set_xlabel`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xlabel)
### ylabel
向 y 轴添加轴标签。
命令式:[`matplotlib.pyplot.ylabel`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.ylabel),面向对象:[`matplotlib.axes.Axes.set_ylabel`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_ylabel)
### title
`Axes`添加标题。
命令式:[`matplotlib.pyplot.title`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.title),面向对象:[`matplotlib.axes.Axes.set_title`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_title)
### figtext
`Figure`的任意位置添加文本。
命令式:[`matplotlib.pyplot.figtext`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figtext),面向对象:[`matplotlib.figure.Figure.text`](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.text)
### suptitle
`Figure`添加标题。
命令式:[`matplotlib.pyplot.suptitle`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.suptitle),面向对象:[`matplotlib.figure.Figure.suptitle`](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.suptitle)
### annotate
`Axes`添加标注,带有可选的箭头。
命令式:[`matplotlib.pyplot.annotate`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.annotate),面向对象:[`matplotlib.axes.Axes.annotate`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.annotate)
所有这些函数创建并返回一个`matplotlib.text.Text()`实例,它可以配置各种字体和其他属性。 下面的示例在实战中展示所有这些命令。
```py
# -*- 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()
```
![](http://matplotlib.org/_images/text_commands.png)
## 文本属性及布局
`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 | [ 点的尺寸 | 相对尺寸,例如 `['smaller', 'x-large' ]` |
| 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 | 任意数值 |
您可以使用对齐参数`horizontalalignment`,`verticalalignment`和`multialignment`来布置文本。 `horizontalalignment`控制文本的`x`位置参数表示文本边界框的左边,中间或右边。 `verticalalignment`控制文本的`y`位置参数表示文本边界框的底部,中心或顶部。 `multialignment`,仅对于换行符分隔的字符串,控制不同的行是左,中还是右对齐。 这里是一个使用`text()`命令显示各种对齐方式的例子。 在整个代码中使用`transform = ax.transAxes`,表示坐标相对于轴边界框给出,其中`0,0`是轴的左下角,`1,1`是右上角。
```py
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()
```
![](http://matplotlib.org/_images/text_layout.png)
## 编写数学表达式
你可以在任何 matplotlib 文本字符串中使用子 TeX 标记,将它放在一对美元符号(`$`)内。
注意,你不需要安装 TeX,因为 matplotlib 提供了自己的 TeX 表达式解析器,布局引擎和字体。 布局引擎是 Donald Knuth 的 TeX 中的布局算法的一种相当直接的适配版,所以质量是相当不错的(matplotlib 还为那些想要调用 TeX 生成文本的人提供一个`usetex`选项(参见[使用 LaTeX 渲染文本](http://matplotlib.org/users/usetex.html#usetex-tutorial) )。
任何文本元素都可以使用数学文本。 你应该使用原始字符串(在引号前面加一个`'r'`),并用美元符号(`$`)包围数学文本,如 TeX。 常规文本和数学文本可以在同一个字符串内交错。 Mathtext 可以使用 Computer Modern 字体(来自 (La)TeX),STIX 字体(为与 Times 混合使用而设计)或您提供的 Unicode 字体。 可以使用自定义变量`mathtext.fontset`选择 mathtext 字体(请参阅[自定义 matplotlib](http://matplotlib.org/users/customizing.html#customizing-matplotlib))
> 注意
> 在Python的 “narrow” 构建中,如果使用 STIX 字体,您还应该将`ps.fonttype`和`pdf.fonttype`设置为 3(默认值),而不是 42。否则一些字符将不可见。
下面是个简单的例子:
```py
# plain text
plt.title('alpha > beta')
```
生成`alpha > beta`。
但是这个:
```py
# math text
plt.title(r'$\alpha > \beta$')
```
生成 ![](http://matplotlib.org/_images/mathmpl/math-3ba37e0517.png)。
> 注意
> Mathtext 应该放在一对美元符号(`$`)之间。 为了易于显示货币值,例如`$ 100.00`,如果整个字符串中存在单个美元符号,则它将被逐字显示为美元符号。 这是常规 TeX 的一个小改变,其中非数学文本中的美元符号必须被转义(`'$'`)。
> 注意
> 虽然一对美元符号(`$`)内的语法是 TeX 风格的,但是外面的文本不是。 特别是,字符:
> ```
> # $ % & ~ _ ^ \ { } \( \) \[ \]
> ```
> 在 TeX 中的数学模式之外有特殊的意义。 因此,根据`rcParam text.usetex`标志这些字符的表现有所不同。 更多信息请参阅[`usetex`教程](http://matplotlib.org/users/usetex.html#usetex-tutorial)。
### 下标和上标
为了制作下标和上标,使用`_`或者`^`符号:
```py
r'$\alpha_i > \beta_i$'
```
![](http://matplotlib.org/_images/mathmpl/math-e2db32b4d0.png)
一些符号会自动将它们的下标或上标放在操作符的底部或顶部,例如,为了编写 0 到无穷的 ![](http://matplotlib.org/_images/mathmpl/math-ccea9f4e30.png) 的和,你可以:
```py
r'$\sum_{i=0}^\infty x_i$'
```
![](http://matplotlib.org/_images/mathmpl/math-a3ca6be911.png)
### 分数、二项式和堆叠数
可以使用`\frac{}{}`,`\binomial{}{}`和`\stackrel{}{}`命令分别创建分数,二项式和堆叠数字:
```py
r'$\frac{3}{4} \binom{3}{4} \stackrel{3}{4}$'
```
产生
![](http://matplotlib.org/_images/mathmpl/math-3025afbc71.png)
分数可以任意嵌套:
```py
r'$\frac{5 - \frac{1}{x}}{4}$'
```
产生
![](http://matplotlib.org/_images/mathmpl/math-2e885fe67f.png)
请注意,在分数周围放置圆括号和花括号需要特别注意。 这种明显的方式会产生太小的括号:
```py
r'$(\frac{5 - \frac{1}{x}}{4})$'
```
![](http://matplotlib.org/_images/mathmpl/math-07b17ba8f6.png)
解决方案是在括号前面加上`\left`和`\right`以通知解析器这些括号包含整个对象:
```py
r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'
```
![](http://matplotlib.org/_images/mathmpl/math-9d267a8c3c.png)
### 根式
根式可以有`\sqrt[]{}`产生,例如:
```py
r'$\sqrt{2}$'
```
![](http://matplotlib.org/_images/mathmpl/math-f151e9b6c6.png)
方括号内可以(可选地)设置任何基底。 请注意,基数必须是一个简单的表达式,并且不能包含布局命令,如分数或上下标:
```py
r'$\sqrt[3]{x}$'
```
![](http://matplotlib.org/_images/mathmpl/math-6b6cc30aef.png)
### 字体
用于数学符号的默认字体是斜体。
> 注意
> 此默认值可以使用`mathtext.default` `rcParam`更改。 这是非常有用的,例如,通过将其设置为`regular`,使用与常规非数学文本相同的字体作为数学文本。
为了修改字体,例如,以 Roman 字体编写`sin`,在字体命令中闭合文本:
```py
r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$'
```
![](http://matplotlib.org/_images/mathmpl/math-c8056d47b3.png)
这里`s`和`t`是斜体(默认)的变量,`sin`是罗马字体,振幅`A`是书法字体。 注意在上面的例子中,`A`和`sin`之间的间距被挤压。 您可以使用间距命令在它们之间添加一些空格:
```py
s(t) = \mathcal{A}\/\sin(2 \omega t)
```
![](http://matplotlib.org/_images/mathmpl/math-44f45b7160.png)
所有字体的可用选项为:
<table border="1" class="docutils">
<colgroup>
<col width="45%" />
<col width="55%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Command</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal"><span class="pre">\mathrm{Roman}</span></code></td>
<td><img src="../_images/mathmpl/math-89f87a2f0c.png" style="position: relative; bottom: -3px"/></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">\mathit{Italic}</span></code></td>
<td><img src="../_images/mathmpl/math-968de0e26b.png" style="position: relative; bottom: -3px"/></td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">\mathtt{Typewriter}</span></code></td>
<td><img src="../_images/mathmpl/math-ca3f612baa.png" style="position: relative; bottom: -8px"/></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">\mathcal{CALLIGRAPHY}</span></code></td>
<td><img src="../_images/mathmpl/math-1f62587cf2.png" style="position: relative; bottom: -5px"/></td>
</tr>
</tbody>
</table>
使用 STIX 字体时,你也可以选择:
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Command</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal"><span class="pre">\mathbb{blackboard}</span></code></td>
<td><img src="../_images/mathmpl/math-a12676f03f.png" style="position: relative; bottom: -3px"/></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">\mathrm{\mathbb{blackboard}}</span></code></td>
<td><img src="../_images/mathmpl/math-014e74dc81.png" style="position: relative; bottom: -3px"/></td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">\mathfrak{Fraktur}</span></code></td>
<td><img src="../_images/mathmpl/math-4f55ade322.png" style="position: relative; bottom: -7px"/></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">\mathsf{sansserif}</span></code></td>
<td><img src="../_images/mathmpl/math-e9444fe0c8.png" style="position: relative; bottom: -3px"/></td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">\mathrm{\mathsf{sansserif}}</span></code></td>
<td><img src="../_images/mathmpl/math-c3a13bbc63.png" style="position: relative; bottom: -3px"/></td>
</tr>
</tbody>
</table>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">\mathcircled{circled}</span></code></td>
<td><img src="../_images/mathmpl/math-e82daa3fb7.png" style="position: relative; bottom: -3px"/></td>
</tr>
</tbody>
</table>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册