提交 e9283187 编写于 作者: W wizardforcel

v2.0

上级 a0fa2377
# 3.1 pyplot 教程
# pyplot 教程
> 原文:[Pyplot tutorial](http://matplotlib.org/users/pyplot_tutorial.html)
......
# 3.2 使用样式表自定义绘图
# 图像教程
> 原文:[Customizing plots with style sheets](http://matplotlib.org/users/style_sheets.html)
> 原文:[Image tutorial](http://matplotlib.org/users/image_tutorial.html)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
`style`包为易于切换的绘图『样式』增加了支持,它们与`matplotlibrc`文件参数相同。
## 启动命令
有一些预定义样式由`matplotlib`提供。 例如,有一个名为『ggplot』的预定义样式,它模拟`ggplot`(R 的一种流行的绘图软件包)的美学。 为了使用此样式,只需添加:
首先,让我们启动 IPython。 它是 Python 标准提示符的最好的改进,它与 Matplotlib 配合得相当不错。 在 shell 或 IPython Notebook 上都可以启动 IPython。
随着 IPython 启动,我们现在需要连接到 GUI 事件循环。 它告诉 IPython 在哪里(以及如何显示)绘图。 要连接到 GUI 循环,请在 IPython 提示符处执行`%matplotlib`魔法。 在 [IPython 的 GUI 事件循环文档](http://ipython.org/ipython-doc/2/interactive/reference.html#gui-event-loop-support)中有更多的细节。
如果使用 IPython Notebook,可以使用相同的命令,但人们通常以特定参数使用`%matplotlib`
```
In [1]: %matplotlib inline
```
这将打开内联绘图,绘图图形将显示在笔记本中。 这对交互性有很重要的影响。 对于内联绘图,在单元格下方的单元格中输出绘图的命令不会影响绘图。 例如,从创建绘图的单元格下面的单元格更改颜色表是不可能的。 但是,对于其他后端,例如 qt4,它们会打开一个单独的窗口,那些创建绘图的单元格下方的单元格将改变绘图 - 它是一个内存中的活对象。
本教程将使用`matplotlib`的命令式绘图接口`pyplot`。 该接口维护全局状态,并且可用于简单快速地尝试各种绘图设置。 另一种是面向对象的接口,这也非常强大,一般更适合大型应用程序的开发。 如果你想了解面向对象接口,[使用上的常见问题](http://matplotlib.org/faq/usage_faq.html)是一个用于起步的不错的页面。 现在,让我们继续使用命令式方式:
```py
In [2]: import matplotlib.pyplot as plt
In [3]: import matplotlib.image as mpimg
In [4]: import numpy as np
```
## 将图像数据导入到 NumPy 数组
加载图像数据由 Pillow 库提供支持。 本来,`matplotlib`只支持 PNG 图像。 如果本机读取失败,下面显示的命令会回退到 Pillow。
此示例中使用的图像是 PNG 文件,但是请记住你自己的数据的 Pillow 要求。
下面是我们要摆弄的图片:
![](http://matplotlib.org/_images/stinkbug.png)
它是一个 24 位 RGB PNG 图像(每个 R,G,B 为 8 位)。 根据你获取数据的位置,你最有可能遇到的其他类型的图像是 RGBA 图像,拥有透明度或单通道灰度(亮度)的图像。 你可以右键单击它,选择`Save image as`(另存为)为本教程的剩余部分下载到你的计算机。
现在我们开始...
```py
In [5]: img=mpimg.imread('stinkbug.png')
Out[5]:
array([[[ 0.40784314, 0.40784314, 0.40784314],
[ 0.40784314, 0.40784314, 0.40784314],
[ 0.40784314, 0.40784314, 0.40784314],
...,
[ 0.42745098, 0.42745098, 0.42745098],
[ 0.42745098, 0.42745098, 0.42745098],
[ 0.42745098, 0.42745098, 0.42745098]],
...,
[[ 0.44313726, 0.44313726, 0.44313726],
[ 0.4509804 , 0.4509804 , 0.4509804 ],
[ 0.4509804 , 0.4509804 , 0.4509804 ],
...,
[ 0.44705883, 0.44705883, 0.44705883],
[ 0.44705883, 0.44705883, 0.44705883],
[ 0.44313726, 0.44313726, 0.44313726]]], dtype=float32)
```
注意这里的`dtype` - `float32`。 Matplotlib 已将每个通道的8位数据重新定标为 0.0 和 1.0 之间的浮点数。 作为旁注,Pillow 可以使用的唯一数据类型是`uint8`。 Matplotlib 绘图可以处理`float32``uint8`,但是对于除 PNG 之外的任何格式的图像,读取/写入仅限于`uint8`数据。 为什么是 8 位呢? 大多数显示器只能渲染每通道 8 位的颜色渐变。 为什么他们只能渲染每通道 8 位呢? 因为这会使所有人的眼睛可以看到。 更多信息请见(从摄影的角度):[Luminous Landscape 位深度教程](http://www.luminous-landscape.com/tutorials/bit-depth.shtml)
每个内部列表表示一个像素。 这里,对于 RGB 图像,有 3 个值。 由于它是一个黑白图像,R,G 和 B 都是类似的。 RGBA(其中 A 是阿尔法或透明度)对于每个内部列表具有 4 个值,而且简单亮度图像仅具有一个值(因此仅是二维数组,而不是三维数组)。 对于 RGB 和 RGBA 图像,`matplotlib`支持`float32``uint8`数据类型。 对于灰度,`matplotlib`只支持`float32`。 如果你的数组数据不符合这些描述之一,则需要重新缩放它。
## 将 NumPy 数组绘制为图像
所以,你将数据保存在一个`numpy`数组(通过导入它,或生成它)。 让我们渲染它吧。 在 Matplotlib 中,这是使用`imshow()`函数执行的。 这里我们将抓取`plot`对象。 这个对象提供了一个简单的方法来从提示符处理绘图。
```py
In [6]: imgplot = plt.imshow(img)
```
![](http://matplotlib.org/_images/image_tutorial-1.png)
你也可以绘制任何 NumPy 数组。
### 对图像绘图应用伪彩色方案
伪彩色可以是一个有用的工具,用于增强对比度和更易于可视化你的数据。 这在使用投影仪对你的数据进行演示时尤其有用 - 它们的对比度通常很差。
伪彩色仅与单通道,灰度,亮度图像相关。 我们目前有一个RGB图像。 由于R,G 和 B 都是相似的(见上面或你的数据),我们可以只选择一个通道的数据:
```py
>>> import matplotlib.pyplot as plt
>>> plt.style.use('ggplot')
In [7]: lum_img = img[:,:,0]
```
为了列出所有可用样式,使用:
这是数组切片,更多信息请见[NumPy 教程](http://www.scipy.org/Tentative_NumPy_Tutorial)
```py
>>> print(plt.style.available)
In [8]: plt.imshow(lum_img)
```
## 定义你自己的样式
![](http://matplotlib.org/_images/image_tutorial-2.png)
你可以创建自定义样式,并通过以样式表的路径或 URL 调用`style.use`来使用它们。 或者,如果将`<style-name> mplstyle`文件添加到`mpl_configdir /stylelib`中,你可以通过调用`style.use(<style-name>)`重复使用自定义样式表。 默认情况下`mpl_configdir`应该是`~/.config/matplotlib`,但你可以使用`matplotlib.get_configdir()`检查你的位置,你可能需要创建这个目录。 请注意,如果样式具有相同的名称,`mpl_configdir/stylelib`中的自定义样式表将覆盖由`matplotlib`定义的样式表
现在,亮度(2D,无颜色)图像应用了默认颜色表(也称为查找表,LUT)。 默认值称为`jet`。 有很多其他方案可以选择
例如,你可能想要使用以下命令创建`mpl_configdir/stylelib/presentation.mplstyle`
```py
In [9]: plt.imshow(lum_img, cmap="hot")
```
![](http://matplotlib.org/_images/image_tutorial-3.png)
请注意,你还可以使用`set_cmap()`方法更改现有绘图对象上的颜色:
```py
In [10]: imgplot = plt.imshow(lum_img)
In [11]: imgplot.set_cmap('spectral')
```
![](http://matplotlib.org/_images/image_tutorial-4.png)
> 注
> 但是,请记住,在带有内联后端的 IPython notebook 中,你不能对已经渲染的绘图进行更改。 如果你在一个单元格中创建了`imgplot`,你不能在以后的单元格中调用`set_cmap()`,并且改变前面的绘图。 请确保你在相同单元格中一起输入这些命令。`plt`命令不会更改先前单元格的绘图。
有许多可选的其它颜色表,请见[颜色表的列表和图像](http://matplotlib.org/examples/color/colormaps_reference.html)
### 颜色刻度参考
了解颜色代表什么值对我们很有帮助。 我们可以通过添加颜色条来做到这一点。
```py
In [12]: imgplot = plt.imshow(lum_img)
In [13]: plt.colorbar()
```
axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16
![](http://matplotlib.org/_images/image_tutorial-5.png)
这会为你现有的图形添加一个颜色条。 如果你更改并切换到不同的颜色映射,则不会自动更改 - 你必须重新创建绘图,并再次添加颜色条。
### 检查特定数据范围
有时,你想要增强图像的对比度,或者扩大特定区域的对比度,同时牺牲变化不大,或者无所谓的颜色细节。 找到有趣区域的最好工具是直方图。 要创建我们的图像数据的直方图,我们使用`hist()`函数。
```py
In [14]: plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
```
然后,当你想要将一个为纸张设计的地图迁移到演示文档中时,你可以添加:
![](http://matplotlib.org/_images/image_tutorial-6.png)
通常,图像的『有趣』部分在峰值附近,你可以通过剪切峰值上方和/或下方的区域获得额外的对比度。 在我们的直方图中,看起来最大值处没有太多有用的信息(图像中有很多不是白色的东西)。 让我们调整上限,以便我们有效地『放大』直方图的一部分。 我们通过将`clim`参数传递给`imshow`来实现。 你也可以通过对图像绘图对象调用`set_clim()`方法来做到这一点,但要确保你在使用 IPython Notebook 的时候,和`plot`命令在相同的单元格中执行 - 它不会改变之前单元格的图。
```py
>>> import matplotlib.pyplot as plt
>>> plt.style.use('presentation')
In [15]: imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
```
## 组合样式
![](http://matplotlib.org/_images/image_tutorial-7.png)
### 数组插值方案
插值根据不同的数学方案计算像素『应有』的颜色或值。 发生这种情况的一个常见的场景是调整图像的大小。 像素的数量会发生变化,但你想要相同的信息。 由于像素是离散的,因此存在缺失的空间。 插值就是填补这个空间的方式。 这就是当你放大图像时,你的图像有时会出来看起来像素化的原因。 当原始图像和扩展图像之间的差异较大时,效果更加明显。 让我们加载我们的图像并缩小它。 我们实际上正在丢弃像素,只保留少数几个像素。 现在,当我们绘制它时,数据被放大为你屏幕的大小。 由于旧的像素不再存在,计算机必须绘制像素来填充那个空间。
样式表为组合在一起而设计。 因此,你可以拥有一个自定义颜色的样式表和一个单独的样式表,用于更改演示文档的元素大小。 这些样式可以通过传递样式列表轻松组合:
我们将使用用来加载图像的 Pillow 库来调整图像大小。
```py
>>> import matplotlib.pyplot as plt
>>> plt.style.use(['dark_background', 'presentation'])
In [16]: from PIL import Image
In [17]: img = Image.open('../_static/stinkbug.png')
In [18]: img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
In [19]: imgplot = plt.imshow(img)
```
请注意,右侧的样式将覆盖已经由左侧样式定义的值。
![](http://matplotlib.org/_images/image_tutorial-8.png)
## 临时样式
这里我们使用默认插值,双线性,因为我们没有向`imshow()`提供任何插值参数。
如果只想对特定的代码块使用样式,但不想更改全局样式,那么样式包提供了一个上下文管理器,用于将更改限制于特定范围。 要隔离你的样式更改,你可以编写以下内容:
让我们试试一些其它的东西:
最邻近
```py
In [20]: imgplot = plt.imshow(img, interpolation="nearest")
```
![](http://matplotlib.org/_images/image_tutorial-9.png)
双立方
```py
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> with plt.style.context(('dark_background')):
>>> plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
>>>
>>> # Some plotting code with the default style
>>>
>>> plt.show()
In [21]: imgplot = plt.imshow(img, interpolation="bicubic")
```
![](http://matplotlib.org/_images/image_tutorial-10.png)
双立方插值通常用于放大照片 - 人们倾向于模糊而不是过度像素化。
# 3.5 图像教程
> 原文:[Image tutorial](http://matplotlib.org/users/image_tutorial.html)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 启动命令
首先,让我们启动 IPython。 它是 Python 标准提示符的最好的改进,它与 Matplotlib 配合得相当不错。 在 shell 或 IPython Notebook 上都可以启动 IPython。
随着 IPython 启动,我们现在需要连接到 GUI 事件循环。 它告诉 IPython 在哪里(以及如何显示)绘图。 要连接到 GUI 循环,请在 IPython 提示符处执行`%matplotlib`魔法。 在 [IPython 的 GUI 事件循环文档](http://ipython.org/ipython-doc/2/interactive/reference.html#gui-event-loop-support)中有更多的细节。
如果使用 IPython Notebook,可以使用相同的命令,但人们通常以特定参数使用`%matplotlib`
```
In [1]: %matplotlib inline
```
这将打开内联绘图,绘图图形将显示在笔记本中。 这对交互性有很重要的影响。 对于内联绘图,在单元格下方的单元格中输出绘图的命令不会影响绘图。 例如,从创建绘图的单元格下面的单元格更改颜色表是不可能的。 但是,对于其他后端,例如 qt4,它们会打开一个单独的窗口,那些创建绘图的单元格下方的单元格将改变绘图 - 它是一个内存中的活对象。
本教程将使用`matplotlib`的命令式绘图接口`pyplot`。 该接口维护全局状态,并且可用于简单快速地尝试各种绘图设置。 另一种是面向对象的接口,这也非常强大,一般更适合大型应用程序的开发。 如果你想了解面向对象接口,[使用上的常见问题](http://matplotlib.org/faq/usage_faq.html)是一个用于起步的不错的页面。 现在,让我们继续使用命令式方式:
```py
In [2]: import matplotlib.pyplot as plt
In [3]: import matplotlib.image as mpimg
In [4]: import numpy as np
```
## 将图像数据导入到 NumPy 数组
加载图像数据由 Pillow 库提供支持。 本来,`matplotlib`只支持 PNG 图像。 如果本机读取失败,下面显示的命令会回退到 Pillow。
此示例中使用的图像是 PNG 文件,但是请记住你自己的数据的 Pillow 要求。
下面是我们要摆弄的图片:
![](http://matplotlib.org/_images/stinkbug.png)
它是一个 24 位 RGB PNG 图像(每个 R,G,B 为 8 位)。 根据你获取数据的位置,你最有可能遇到的其他类型的图像是 RGBA 图像,拥有透明度或单通道灰度(亮度)的图像。 你可以右键单击它,选择`Save image as`(另存为)为本教程的剩余部分下载到你的计算机。
现在我们开始...
```py
In [5]: img=mpimg.imread('stinkbug.png')
Out[5]:
array([[[ 0.40784314, 0.40784314, 0.40784314],
[ 0.40784314, 0.40784314, 0.40784314],
[ 0.40784314, 0.40784314, 0.40784314],
...,
[ 0.42745098, 0.42745098, 0.42745098],
[ 0.42745098, 0.42745098, 0.42745098],
[ 0.42745098, 0.42745098, 0.42745098]],
...,
[[ 0.44313726, 0.44313726, 0.44313726],
[ 0.4509804 , 0.4509804 , 0.4509804 ],
[ 0.4509804 , 0.4509804 , 0.4509804 ],
...,
[ 0.44705883, 0.44705883, 0.44705883],
[ 0.44705883, 0.44705883, 0.44705883],
[ 0.44313726, 0.44313726, 0.44313726]]], dtype=float32)
```
注意这里的`dtype` - `float32`。 Matplotlib 已将每个通道的8位数据重新定标为 0.0 和 1.0 之间的浮点数。 作为旁注,Pillow 可以使用的唯一数据类型是`uint8`。 Matplotlib 绘图可以处理`float32``uint8`,但是对于除 PNG 之外的任何格式的图像,读取/写入仅限于`uint8`数据。 为什么是 8 位呢? 大多数显示器只能渲染每通道 8 位的颜色渐变。 为什么他们只能渲染每通道 8 位呢? 因为这会使所有人的眼睛可以看到。 更多信息请见(从摄影的角度):[Luminous Landscape 位深度教程](http://www.luminous-landscape.com/tutorials/bit-depth.shtml)
每个内部列表表示一个像素。 这里,对于 RGB 图像,有 3 个值。 由于它是一个黑白图像,R,G 和 B 都是类似的。 RGBA(其中 A 是阿尔法或透明度)对于每个内部列表具有 4 个值,而且简单亮度图像仅具有一个值(因此仅是二维数组,而不是三维数组)。 对于 RGB 和 RGBA 图像,`matplotlib`支持`float32``uint8`数据类型。 对于灰度,`matplotlib`只支持`float32`。 如果你的数组数据不符合这些描述之一,则需要重新缩放它。
## 将 NumPy 数组绘制为图像
所以,你将数据保存在一个`numpy`数组(通过导入它,或生成它)。 让我们渲染它吧。 在 Matplotlib 中,这是使用`imshow()`函数执行的。 这里我们将抓取`plot`对象。 这个对象提供了一个简单的方法来从提示符处理绘图。
```py
In [6]: imgplot = plt.imshow(img)
```
![](http://matplotlib.org/_images/image_tutorial-1.png)
你也可以绘制任何 NumPy 数组。
### 对图像绘图应用伪彩色方案
伪彩色可以是一个有用的工具,用于增强对比度和更易于可视化你的数据。 这在使用投影仪对你的数据进行演示时尤其有用 - 它们的对比度通常很差。
伪彩色仅与单通道,灰度,亮度图像相关。 我们目前有一个RGB图像。 由于R,G 和 B 都是相似的(见上面或你的数据),我们可以只选择一个通道的数据:
```py
In [7]: lum_img = img[:,:,0]
```
这是数组切片,更多信息请见[NumPy 教程](http://www.scipy.org/Tentative_NumPy_Tutorial)
```py
In [8]: plt.imshow(lum_img)
```
![](http://matplotlib.org/_images/image_tutorial-2.png)
现在,亮度(2D,无颜色)图像应用了默认颜色表(也称为查找表,LUT)。 默认值称为`jet`。 有很多其他方案可以选择。
```py
In [9]: plt.imshow(lum_img, cmap="hot")
```
![](http://matplotlib.org/_images/image_tutorial-3.png)
请注意,你还可以使用`set_cmap()`方法更改现有绘图对象上的颜色:
```py
In [10]: imgplot = plt.imshow(lum_img)
In [11]: imgplot.set_cmap('spectral')
```
![](http://matplotlib.org/_images/image_tutorial-4.png)
> 注
> 但是,请记住,在带有内联后端的 IPython notebook 中,你不能对已经渲染的绘图进行更改。 如果你在一个单元格中创建了`imgplot`,你不能在以后的单元格中调用`set_cmap()`,并且改变前面的绘图。 请确保你在相同单元格中一起输入这些命令。`plt`命令不会更改先前单元格的绘图。
有许多可选的其它颜色表,请见[颜色表的列表和图像](http://matplotlib.org/examples/color/colormaps_reference.html)
### 颜色刻度参考
了解颜色代表什么值对我们很有帮助。 我们可以通过添加颜色条来做到这一点。
```py
In [12]: imgplot = plt.imshow(lum_img)
In [13]: plt.colorbar()
```
![](http://matplotlib.org/_images/image_tutorial-5.png)
这会为你现有的图形添加一个颜色条。 如果你更改并切换到不同的颜色映射,则不会自动更改 - 你必须重新创建绘图,并再次添加颜色条。
### 检查特定数据范围
有时,你想要增强图像的对比度,或者扩大特定区域的对比度,同时牺牲变化不大,或者无所谓的颜色细节。 找到有趣区域的最好工具是直方图。 要创建我们的图像数据的直方图,我们使用`hist()`函数。
```py
In [14]: plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
```
![](http://matplotlib.org/_images/image_tutorial-6.png)
通常,图像的『有趣』部分在峰值附近,你可以通过剪切峰值上方和/或下方的区域获得额外的对比度。 在我们的直方图中,看起来最大值处没有太多有用的信息(图像中有很多不是白色的东西)。 让我们调整上限,以便我们有效地『放大』直方图的一部分。 我们通过将`clim`参数传递给`imshow`来实现。 你也可以通过对图像绘图对象调用`set_clim()`方法来做到这一点,但要确保你在使用 IPython Notebook 的时候,和`plot`命令在相同的单元格中执行 - 它不会改变之前单元格的图。
```py
In [15]: imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))
```
![](http://matplotlib.org/_images/image_tutorial-7.png)
### 数组插值方案
插值根据不同的数学方案计算像素『应有』的颜色或值。 发生这种情况的一个常见的场景是调整图像的大小。 像素的数量会发生变化,但你想要相同的信息。 由于像素是离散的,因此存在缺失的空间。 插值就是填补这个空间的方式。 这就是当你放大图像时,你的图像有时会出来看起来像素化的原因。 当原始图像和扩展图像之间的差异较大时,效果更加明显。 让我们加载我们的图像并缩小它。 我们实际上正在丢弃像素,只保留少数几个像素。 现在,当我们绘制它时,数据被放大为你屏幕的大小。 由于旧的像素不再存在,计算机必须绘制像素来填充那个空间。
我们将使用用来加载图像的 Pillow 库来调整图像大小。
```py
In [16]: from PIL import Image
In [17]: img = Image.open('../_static/stinkbug.png')
In [18]: img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
In [19]: imgplot = plt.imshow(img)
```
![](http://matplotlib.org/_images/image_tutorial-8.png)
这里我们使用默认插值,双线性,因为我们没有向`imshow()`提供任何插值参数。
让我们试试一些其它的东西:
最邻近
```py
In [20]: imgplot = plt.imshow(img, interpolation="nearest")
```
![](http://matplotlib.org/_images/image_tutorial-9.png)
双立方
```py
In [21]: imgplot = plt.imshow(img, interpolation="bicubic")
```
![](http://matplotlib.org/_images/image_tutorial-10.png)
双立方插值通常用于放大照片 - 人们倾向于模糊而不是过度像素化。
# 3.6 图例指南
# 图例指南
> 原文:[Legend guide](http://matplotlib.org/users/legend_guide.html)
......
# 第三章 入门指南
# 教程
# 引言
> 原文:[Text introduction](http://matplotlib.org/users/text_intro.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 数学符号和命令,来支持你图中任何地方放置数学表达式。
\ No newline at end of file
# 基本的文本命令
> 原文:[Basic text commands](http://matplotlib.org/users/text_intro.html#basic-text-commands)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 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)
\ No newline at end of file
# 文本属性及布局
> 原文:[Text properties and layout](http://matplotlib.org/users/text_props.html)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
`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)
\ No newline at end of file
# 3.7 轴域标注
# 标注
> 原文:[Annotating Axes](http://matplotlib.org/users/annotations_guide.html)
> 原文:[Annotation](http://matplotlib.org/users/annotations.html)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 轴域标注
## 高级标注
除非你已经读过了[文本标注](http://matplotlib.org/users/annotations_intro.html#annotations-tutorial)[`text()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text)[`annotate()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.annotate),否则不要继续往下看。
## 使用框和文本来标注
### 使用框和文本来标注
让我们以一个简单的例子来开始。
......@@ -56,7 +54,7 @@ bb.set_boxstyle("rarrow", pad=0.6)
bb.set_boxstyle("rarrow,pad=0.6")
```
## 使用箭头来标注
### 使用箭头来标注
`pyplot`模块(或`Axes`类的`annotate`方法)中的`annotate()`函数用于绘制连接图上两点的箭头。
......@@ -155,7 +153,7 @@ ax.annotate("",
![](http://matplotlib.org/_images/annotate_simple04.png)
## 将 artist 放置在轴域的锚定位置
### 将 artist 放置在轴域的锚定位置
有一类 artist 可以放置在轴域的锚定位置。 一个常见的例子是图例。 这种类型的 artist 可以使用`OffsetBox`类创建。 `mpl_toolkits.axes_grid.anchored_artists`中有几个预定义类。
......@@ -218,7 +216,7 @@ box.drawing_area.add_artist(el)
请注意,与图例不同,默认情况下,`bbox_transform`设置为`IdentityTransform`
## 使用复杂坐标来标注
### 使用复杂坐标来标注
matplotlib 中的标注支持[标注文本](http://matplotlib.org/users/annotations_intro.html#annotations-tutorial)中描述的几种类型的坐标。 对于想要更多控制的高级用户,它支持几个其他选项。
......
# 3.4 文本处理
# 编写数学表达式
> 原文:[Working with text](http://matplotlib.org/users/index_text.html)
> 原文:[Writing mathematical expressions](http://matplotlib.org/users/mathtext.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) )。
......@@ -262,7 +48,7 @@ plt.title(r'$\alpha > \beta$')
> 在 TeX 中的数学模式之外有特殊的意义。 因此,根据`rcParam text.usetex`标志这些字符的表现有所不同。 更多信息请参阅[`usetex`教程](http://matplotlib.org/users/usetex.html#usetex-tutorial)。
### 下标和上标
## 下标和上标
为了制作下标和上标,使用`_`或者`^`符号:
......@@ -280,7 +66,7 @@ r'$\sum_{i=0}^\infty x_i$'
![](http://matplotlib.org/_images/mathmpl/math-a3ca6be911.png)
### 分数、二项式和堆叠数
## 分数、二项式和堆叠数
可以使用`\frac{}{}``\binomial{}{}``\stackrel{}{}`命令分别创建分数,二项式和堆叠数字:
......@@ -318,7 +104,7 @@ r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$'
![](http://matplotlib.org/_images/mathmpl/math-9d267a8c3c.png)
### 根式
## 根式
根式可以有`\sqrt[]{}`产生,例如:
......@@ -336,7 +122,7 @@ r'$\sqrt[3]{x}$'
![](http://matplotlib.org/_images/mathmpl/math-6b6cc30aef.png)
### 字体
## 字体
用于数学符号的默认字体是斜体。
......@@ -397,7 +183,7 @@ s(t) = \mathcal{A}\/\sin(2 \omega t)
此外,你可以使用`\mathdefault{...}`或其别名`\mathregular{...}`来使用用于 mathtext 之外的常规文本的字体。 这种方法有一些限制,最明显的是,可以使用很少的符号,但可用于将数学表达式与图中的其他文本混合。
### 自定义字体
## 自定义字体
mathtext 还提供了一种对数学公式使用自定义字体的方法。 这种方法使用起来相当棘手,应该看做为有耐心的用户准备的试验特性。 通过将`rcParam mathtext.fontset`设置为`custom`,你可以设置以下参数,这些参数控制用于特定数学字符集的字体文件。
......@@ -416,7 +202,7 @@ mathtext 还提供了一种对数学公式使用自定义字体的方法。 这
请注意,Unicode 中规定的数学字形随时间而演进,许多字体的字形对于 mathtext 可能不在正确位置。
### 重音符号
## 重音符号
重音命令可以位于任何符号之前,在其上添加重音。 他们中的一些些拥有较长和较短的形式。
......@@ -448,7 +234,7 @@ r"$\hat i\ \ \hat \imath$"
![](http://matplotlib.org/_images/mathmpl/math-80117b16d3.png)
### 符号
## 符号
你也可以使用更大量的 TeX 符号,比如`\infty``\leftarrow``\sum``\int`
......@@ -636,7 +422,7 @@ r"$\hat i\ \ \hat \imath$"
ur'$\u23ce$'
```
### 示例
## 示例
下面是个示例,在上下文中展示了许多这些特性。
......
# 文本处理
\ No newline at end of file
# 自定义 matplotlib
> 原文:[Customizing matplotlib](http://matplotlib.org/users/customizing.html)
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 使用样式表自定义绘图
`style`包为易于切换的绘图『样式』增加了支持,它们与`matplotlibrc`文件参数相同。
有一些预定义样式由`matplotlib`提供。 例如,有一个名为『ggplot』的预定义样式,它模拟`ggplot`(R 的一种流行的绘图软件包)的美学。 为了使用此样式,只需添加:
```py
>>> import matplotlib.pyplot as plt
>>> plt.style.use('ggplot')
```
为了列出所有可用样式,使用:
```py
>>> print(plt.style.available)
```
## 定义你自己的样式
你可以创建自定义样式,并通过以样式表的路径或 URL 调用`style.use`来使用它们。 或者,如果将`<style-name> mplstyle`文件添加到`mpl_configdir /stylelib`中,你可以通过调用`style.use(<style-name>)`重复使用自定义样式表。 默认情况下`mpl_configdir`应该是`~/.config/matplotlib`,但你可以使用`matplotlib.get_configdir()`检查你的位置,你可能需要创建这个目录。 请注意,如果样式具有相同的名称,`mpl_configdir/stylelib`中的自定义样式表将覆盖由`matplotlib`定义的样式表。
例如,你可能想要使用以下命令创建`mpl_configdir/stylelib/presentation.mplstyle`
```
axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16
```
然后,当你想要将一个为纸张设计的地图迁移到演示文档中时,你可以添加:
```py
>>> import matplotlib.pyplot as plt
>>> plt.style.use('presentation')
```
## 组合样式
样式表为组合在一起而设计。 因此,你可以拥有一个自定义颜色的样式表和一个单独的样式表,用于更改演示文档的元素大小。 这些样式可以通过传递样式列表轻松组合:
```py
>>> import matplotlib.pyplot as plt
>>> plt.style.use(['dark_background', 'presentation'])
```
请注意,右侧的样式将覆盖已经由左侧样式定义的值。
## 临时样式
如果只想对特定的代码块使用样式,但不想更改全局样式,那么样式包提供了一个上下文管理器,用于将更改限制于特定范围。 要隔离你的样式更改,你可以编写以下内容:
```py
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> with plt.style.context(('dark_background')):
>>> plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
>>>
>>> # Some plotting code with the default style
>>>
>>> plt.show()
```
# 3.3 交互式导航
# 交互式导航
> 原文:[Interactive navigation](http://matplotlib.org/users/navigation_toolbar.html)
......
# 交互式绘图
\ No newline at end of file
# 3.8 屏幕截图
# 屏幕截图
> 原文:[Screenshots](http://matplotlib.org/users/screenshots.html)
......
# 所选示例
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册