提交 a829478e 编写于 作者: W wizardforcel

3.2

上级 656614f5
# 3.2 使用样式表自定义绘图
> 原文:[Customizing plots with style sheets](http://matplotlib.org/users/style_sheets.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()
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册