├── .gitignore ├── 1.md ├── 2.md ├── 3.1.md ├── 3.2.md ├── 3.3.md ├── 3.4.md ├── 3.5.md ├── 3.6.md ├── 3.7.md ├── 3.8.md ├── 3.9.md ├── 3.md ├── 4.1.md ├── 4.2.md ├── 4.3.md ├── 4.4.md ├── 4.5.md ├── 4.6.md ├── 4.7.md ├── 4.8.md ├── 4.md ├── 5.1.md ├── 5.2.md ├── 5.3.md ├── 5.md ├── 6.md ├── 7.1.md ├── 7.2.md ├── 7.3.md ├── 7.md ├── 8.1.md ├── 8.2.md ├── 8.md ├── README.md ├── SUMMARY.md ├── glossary.md └── styles └── ebook.css /.gitignore: -------------------------------------------------------------------------------- 1 | _book 2 | -------------------------------------------------------------------------------- /1.md: -------------------------------------------------------------------------------- 1 | # 简介 2 | 3 | > 原文:[Introduction](http://matplotlib.org/users/intro.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | Matplotlib 是一个用于在 [Python](https://www.python.org/) 中绘制数组的 2D 图形库。虽然它起源于模仿 MATLAB®[1] 图形命令,但它独立于 MATLAB,可以以 Pythonic 和面向对象的方式使用。虽然 Matplotlib 主要是在纯 Python 中编写的,但它大量使用 [NumPy](http://www.numpy.org/) 和其他扩展代码,即使对于大型数组也能提供良好的性能。 10 | 11 | Matplotlib 的设计理念是,你应该能够使用几个,或者只有一个命令创建简单的图形。如果你想看到你的数据的直方图,你不需要实例化对象,调用方法,设置属性等等;它应该能够工作。 12 | 13 | 多年来,我常常使用 MATLAB 进行数据分析和可视化。 MATLAB 擅长绘制漂亮的图形。当我开始处理 EEG 数据时,我发现我需要编写应用程序来与我的数据交互,并在 MATLAB 中开发了一个 EEG 分析应用程序。随着应用程序越来越复杂,需要与数据库,http 服务器交互,并操作复杂的数据结构,我开始与 MATLAB 作为一种编程语言的限制而抗争,并决定迁移到 Python。 Python 作为一种编程语言,弥补了 MATLAB 的所有缺陷,但我很难找到一个 2D 绘图包(3D [VTK](http://www.vtk.org/) 则超过了我的所有需求)。 14 | 15 | 当我去寻找一个 Python 绘图包时,我有几个要求: 16 | 17 | + 绘图应该看起来不错 - 发布质量。 对我来说一个重要的要求是文本看起来不错(抗锯齿等) 18 | + 用于包含 TeX 文档的 Postscript 输出 19 | + 可嵌入图形用户界面用于应用程序开发 20 | + 代码应该足够容易,我可以理解它,并扩展它 21 | + 绘图应该很容易 22 | 23 | 没有找到适合我的包,我做了任何自称 Python 程序员会做的事情:撸起我的袖子开始自己造。我没有任何真正的计算机图形经验,决定模仿 MATLAB 的绘图功能,因为 MATLAB 做得很好。这有额外的优势,许多人有很多 MATLAB 的经验,因此,他们可以很快开始在 python 中绘图。从开发人员的角度来看,拥有固定的用户接口(pylab 接口)非常有用,因为代码库的内容可以重新设计,而不会影响用户代码。 24 | 25 | Matplotlib 代码在概念上分为三个部分:pylab 接口是由`matplotlib.pylab`提供的函数集,允许用户使用非常类似于 MATLAB 图生成代码([Pyplot 教程](http://matplotlib.org/users/pyplot_tutorial.html#pyplot-tutorial))的代码创建绘图。 Matplotlib 前端或 Matplotlib API 是一组重要的类,创建和管理图形,文本,线条,图表等([艺术家教程](http://matplotlib.org/users/artists.html#artist-tutorial))。这是一个对输出无所了解的抽象接口。后端是设备相关的绘图设备,也称为渲染器,将前端表示转换为打印件或显示设备(什么是后端?)。后端示例:PS 创建 [PostScript®](http://www.adobe.com/products/postscript/) 打印件,SVG 创建[可缩放矢量图形](http://www.w3.org/Graphics/SVG/)打印件,Agg 使用 Matplotlib 附带的高质量[反颗粒几何库](http://antigrain.com/)创建 PNG 输出,GTK 在 [Gtk+](https://www.gtk.org/) 应用程序中嵌入 Matplotlib,GTKAgg 使用反颗粒渲染器创建图形并将其嵌入到 Gtk+ 应用程序中,以及用于 [PDF](https://acrobat.adobe.com/us/en/why-adobe/about-adobe-pdf.html),[WxWidgets](https://www.wxpython.org/),[Tkinter](https://docs.python.org/library/tkinter.html) 等。 26 | 27 | Matplotlib 被很多人在许多不同的上下文中使用。有些人希望自动生成 PostScript 文件以发送给打印机或发布商。其他人在 Web 应用程序服务器上部署 Matplotlib 来生成 PNG 输出,并包含在动态生成的网页中。一些人在 Windows™ 上的 Tkinter 的 Python shell 中以交互方式使用 Matplotlib。我的主要用途是将 Matplotlib 嵌入 Windows,Linux 和 Macintosh OS X 上运行的 Gtk+ EEG 应用程序中。 28 | 29 | > [1] MATLAB 是 MathWorks 公司的注册商标。 30 | -------------------------------------------------------------------------------- /2.md: -------------------------------------------------------------------------------- 1 | # 安装 2 | 3 | > 原文:[Installing](http://matplotlib.org/users/installing.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 有许多安装 matplotlib 的不同方法,最好的方法取决于你使用的操作系统,已经安装的内容以及如何使用它。 为了避免涉及本页上的所有细节(和潜在的复杂性),有几个方便的选项。 10 | 11 | ## 安装预构建包 12 | 13 | ### 多数平台:Python 科学分发包 14 | 15 | 第一个选项是使用已经内置 matplotlib 的预打包的 Python 分发包。 `Continuum.io` Python 分发包(Anaconda 或 miniconda)和 Enthought 分发包(Canopy)都是『在 Windows,OSX 和主流 Linux 平台开箱即用并正常工作』的出色选择。 这两个分发包包括 matplotlib 和许多其他有用的工具。 16 | 17 | ### Linux:使用你的包管理器 18 | 19 | 如果你是用 Linux,你可能更倾向于使用包管理器。matplotlib 是用于多数主流 Linux 发行版的包。 20 | 21 | + Debian / Ubuntu:`sudo apt-get install python-matplotlib` 22 | + Fedora / Redhat:`sudo yum install python-matplotlib` 23 | 24 | Mac OSX:使用`pip` 25 | 26 | 如果你使用 MacOS,你可以使用 Python 标准安装程序[`pip`](https://pypi.python.org/pypi/pip/)来安装 matplotlib 二进制。参见[安装 MacOS 二进制轮子](http://matplotlib.org/faq/installing_faq.html#install-osx-binaries)。 27 | 28 | ### Windows 29 | 30 | 如果你还没有安装 Python,我们建议使用兼容 SciPy 技术栈的 Python 分发版本,如 WinPython,Python(x, y),Enthought Canopy 或 Continuum Anaconda,它们含有 matplotlib 和它的许多依赖,并预装了其他有用的软件包。 31 | 32 | 对于 [Python 的标准安装](https://www.python.org/downloads/),可以使用`pip`安装 matplotlib : 33 | 34 | ``` 35 | python -m pip install -U pip setuptools 36 | python -m pip install matplotlib 37 | ``` 38 | 39 | 如果没有为所有用户安装 Python 2.7 或 3.4,则需要安装 Microsoft Visual C++ 2008(对于 Python 2.7 为 64 位或 32 位)或 Microsoft Visual C++ 2010(对于 Python 3.4 为 64 位或 32 位)再分发包。 40 | 41 | Matplotlib 依赖于 Pillow 来读取和保存 JPEG,BMP 和 TIFF 图像文件。 Matplotlib 需要 MiKTeX 和 GhostScript 来使用LaTeX渲染文本。动画模块需要 FFmpeg,avconv,mencoder 或 ImageMagick。 42 | 43 | 以下后端应该开箱即用:agg,tkagg,ps,pdf 和 svg。对于其他后端,你可能需要安装 pycairo,PyQt4,PyQt5,PySide,wxPython,PyGTK,Tornado 或 GhostScript。 44 | 45 | TkAgg 可能是来自标准 Python shell 或 IPython 的,用于交互式的最佳后端。它被启用为官方二进制文件的默认后端。 Windows 不支持 GTK3。 46 | 47 | PyPI 下载页面上的 Windows 轮子(`* .whl`)不包含测试数据或示例代码。如果你想尝试 matplotlib 源代码中的许多演示,请下载`*.tar.gz`文件并查看`examples`子目录。要运行测试套件,请将源代码发行版中的`lib\matplotlib\tests`和`lib\mpl_toolkits\tests`目录分别复制到`sys.prefix\Lib\site-packages\matplotlib`和`sys.prefix\Lib\site-packages\mpl_toolkits`,并安装 nose,mock,Pillow,MiKTeX,GhostScript,ffmpeg,avconv,mencoder,ImageMagick 和 Inkscape。 48 | 49 | ## 从源码安装 50 | 51 | 如果你有兴趣为 matplotlib 开发做贡献,运行最新的源代码,或者只是想自己构建一切,从源代码构建 matplotlib 并不困难。 [从 PyPI 文件页面](https://pypi.python.org/pypi/matplotlib/)抓取最新的`tar.gz`发布文件,或者如果你想开发 matplotlib 或只需要最新的 bug 修复版本,获取最新的 git 版本,请见[从 git 安装](http://matplotlib.org/faq/installing_faq.html#install-from-git)。 52 | 53 | 源代码遵守标准环境变量 CC,CXX,PKG_CONFIG。 这意味着如果你的工具链有前缀,你可以设置它们。 这可以用于交叉编译。 54 | 55 | ``` 56 | export CC=x86_64-pc-linux-gnu-gcc export CXX=x86_64-pc-linux-gnu-g++ export PKG_CONFIG=x86_64-pc-linux-gnu-pkg-config 57 | ``` 58 | 59 | 一旦你满足的了面的具体需求(主要是 Python、NumPy、libpng 和 freetype),你就可以构建 matplotlib 了: 60 | 61 | ``` 62 | cd matplotlib 63 | python setup.py build 64 | python setup.py install 65 | ``` 66 | 67 | 我们提供与`setup.py`一起使用的`setup.cfg`文件,你可以使用它来自定义构建过程。 例如,要使用的默认后端,是否安装 matplotlib 附带的某些可选库,等等。 这个文件会对那些包装 matplotlib 的东西特别有用。 68 | 69 | 如果已经为非标准设施安装了必备组件,并需要通知 matplotlib 它们在哪里,请编辑`setupext.py`并将基本路径添加为`sys.platform`的`basedir`字典条目。 例如,如果某些所需库的头文件位于`/some/path/include/someheader.h`中,请在你的平台的`basedir`列表中输入`/some/path`。 70 | 71 | ### 构建需求 72 | 73 | 这些是外部软件包,你需要在安装 matplotlib 之前安装它们。 如果你在 OSX 上构建,请参阅[在 OSX 上构建](http://matplotlib.org/users/installing.html#build-osx)。 如果你在 Windows 上构建,请参阅[在 Windows 上构建](http://matplotlib.org/users/installing.html#build-windows)。 如果在 Linux 上使用软件包管理器安装依赖项,则除了库本身之外,还可能需要安装开发包(查找`-dev`后缀)。 74 | 75 | #### 所需依赖 76 | 77 | Python 2.7,3.4,3.5 或 3.6 78 | 79 | [下载 Python](https://www.python.org/downloads/) 80 | 81 | NumPy 1.7.1(或更新) 82 | 83 | Python 的数组支持([下载 NumPy](http://www.numpy.org/)) 84 | 85 | [setuptools](https://setuptools.readthedocs.io/en/latest/) 86 | 87 | setuptools 为 Python 包安装提供扩展 88 | 89 | [dateutil](http://matplotlib.org/glossary/index.html#term-dateutil) 1.1 或更新 90 | 91 | 为 Python 时间日期的处理提供扩展。如果使用了`pip`,`easy_install `或者从源码安装,安装器会尝试从 PyPI 下载并安装`python_dateutil`。 92 | 93 | [pyparsing](https://pyparsing.wikispaces.com/) 94 | 95 | 需要为 matplotlib 的 mathtext 数学渲染提供支持。如果使用了`pip`,`easy_install `或者从源码安装,安装器会尝试从 PyPI 下载并安装`pyparsing`。 96 | 97 | 98 | [libpng 1.2 (或更新)](http://www.libpng.org/) 99 | 100 | 用于加载和保存 [PNG](http://matplotlib.org/glossary/index.html#term-png) 文件([下载](http://www.libpng.org/pub/png/libpng.html))。libong 需要 zlib。 101 | 102 | [pytz](http://pytz.sourceforge.net/) 103 | 104 | 用于操作时区感知的日期时间。 105 | 106 | [FreeType](http://matplotlib.org/glossary/index.html#term-freetype) 2.3 或更新 107 | 108 | 用于读取 TrueType 字体文件。如果使用了`pip`,`easy_install `或者从源码安装,安装器会尝试从预期位置定位 FreeType。如果找病毒奥,尝试安装 [pkg-config](http://matplotlib.org/users/installing.html#optional-dependencies),用于寻找所需非 Python 库的工具。 109 | 110 | [cycler](http://matplotlib.org/cycler/) 0.10.1 或更新 111 | 112 | 可组合的循环类,用于构造 style-cycle。 113 | 114 | [six](https://pypi.python.org/pypi/six) 115 | 116 | 需要用于 Python 2 和 3 之间的兼容性。 117 | 118 | #### Python 2 的依赖 119 | 120 | [functools32](https://pypi.python.org/pypi/functools32) 121 | 122 | 需要用于 Python 2.7 上的兼容性。 123 | 124 | [subprocess32](https://pypi.python.org/pypi/subprocess32/) 125 | 126 | 可选,仅用于 Unix。`subprocess`标准库从 3.2+ 到 2.7 的 Backport。它提供了更好的错误信息和超时支持。 127 | 128 | #### 可选的 GUI 框架 129 | 130 | 这些是可选软件包,你可能希望安装这些软件包来使 用matplotlib 和用户界面工具包。 有关 matplotlib 可选后端和所提供功能的更多详细信息,请参阅[什么是后端](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend)。 131 | 132 | [tk](http://matplotlib.org/glossary/index.html#term-tk) 8.3 或更新,不包括 8.6.0 和 8.6.1 133 | 134 | TkAgg 后端使用的 TCL/Tk 窗口控件库。 135 | 136 | 版本 8.6. 0和 8.6.1 已知有问题,当以错误的顺序关闭多个窗口时可能导致段错误。 137 | 138 | [pyqt](http://matplotlib.org/glossary/index.html#term-pyqt) 4.4 或更新 139 | 140 | Qt4 控件库的 Python 包装,用于 Qt4Agg 后端。 141 | 142 | [pygtk](http://matplotlib.org/glossary/index.html#term-pygtk) 2.4 或更新 143 | 144 | GTK 控件库的 Python 包装,用于 GTK 或者 GTKAgg 后端。 145 | 146 | [wxpython](http://matplotlib.org/glossary/index.html#term-wxpython) 2.8 或更新 147 | 148 | wx 控件库的 Python 包装,用于 WX 或 WXAgg 后端。 149 | 150 | #### 可选的外部程序 151 | 152 | [ffmpeg](https://www.ffmpeg.org/)/[avconv](https://libav.org/avconv.html) 或 [mencoder](http://www.mplayerhq.hu/design7/news.html) 153 | 154 | 需要用于动画模块,将输出保存为电影格式。 155 | 156 | [ImageMagick](http://www.imagemagick.org/script/index.php) 157 | 158 | 需要用于动画模块,能够保存 GIF 动画。 159 | 160 | #### 可选依赖 161 | 162 | [Pillow](http://python-pillow.org/) 163 | 164 | 如果安装了 Pillow,matplotlib 可以读取或写入大部分图像文件格式。 165 | 166 | [pkg-config](https://www.freedesktop.org/wiki/Software/pkg-config/) 167 | 168 | 用于寻找所需非 Python 库的工具。并不是严格需要它,但是如果库和头文件不在预期位置,可以使安装更加便捷。 169 | 170 | #### matplotlib 自带的所需库 171 | 172 | [agg](http://matplotlib.org/glossary/index.html#term-agg) 2.4 173 | 174 | C++ 渲染引擎。 matplotlib 静态链接到 agg 模板源码,所以它除了 matplotlib 之外,不会影响你的系统的任何东西。 175 | 176 | qhull 2012.1 177 | 178 | 用于计算 Delaunay 三角测量的库。 179 | 180 | ttconv 181 | 182 | TureType 字体工具。 183 | 184 | ### 在 Linux 上构建 185 | 186 | 使用你的系统包管理器来安装依赖最为简单。 187 | 188 | 如果你使用 Debian/Ubuntu,可以使用以下命令在获取需要用于构建 matplotlib 的所有依赖: 189 | 190 | ``` 191 | sudo apt-get build-dep python-matplotlib 192 | ``` 193 | 194 | 如果你使用 Fedora/RedHat,你可以使用以下命令: 195 | 196 | ``` 197 | su -c "yum-builddep python-matplotlib" 198 | ``` 199 | 200 | 这不会构建 matplotlib,但这会安装所需依赖。这会使从源码构建变得容易。 201 | 202 | ### 在 OSX 上构建 203 | 204 | 由于可以获取`libpng`和`freetype`需求(darwinports,fink,/usr/X11R6)的不同位置,不同的架构(例如 x86,ppc,universal)和不同的 OSX 版本 10.4 和 10.5),OSX 的构建情况很复杂。我们建议你使用我们对 OSX 版本所做的方式来构建:从`tarball`或`git`仓库获取源代码,并按照`README.osx`中的说明进行操作。 205 | 206 | ### 在 Windows 上构建 207 | 208 | 上发布的 Python ,使用 VS2008 编译 3.3 之前的版本,使用 VS2010 编译 3.3,并且使用 VS2015 编译 3.5 和 3.6。 建议使用相同的编译器编译 Python 扩展。 209 | 210 | 由于没有规范的 Windows 包管理器,从源代码构建`freetype`,`zlib`和`libpng`的方法被记录为`matplotlib-winbuild`中的构建脚本。 211 | -------------------------------------------------------------------------------- /3.1.md: -------------------------------------------------------------------------------- 1 | # pyplot 教程 2 | 3 | > 原文:[Pyplot tutorial](http://matplotlib.org/users/pyplot_tutorial.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | `matplotlib.pyplot`是一个命令风格函数的集合,使`matplotlib`的机制更像 MATLAB。 每个绘图函数对图形进行一些更改:例如,创建图形,在图形中创建绘图区域,在绘图区域绘制一些线条,使用标签装饰绘图等。在`matplotlib.pyplot`中,各种状态跨函数调用保存,以便跟踪诸如当前图形和绘图区域之类的东西,并且绘图函数始终指向当前轴域(请注意,这里和文档中的大多数位置中的『轴域』(axes)是指图形的一部分(两条坐标轴围成的区域),而不是指代多于一个轴的严格数学术语)。 10 | 11 | ```py 12 | import matplotlib.pyplot as plt 13 | plt.plot([1,2,3,4]) 14 | plt.ylabel('some numbers') 15 | plt.show() 16 | ``` 17 | 18 | ![](http://matplotlib.org/_images/pyplot_simple.png) 19 | 20 | 你可能想知道为什么`x`轴的范围为`0-3`,`y`轴的范围为`1-4`。 如果你向`plot()`命令提供单个列表或数组,则`matplotlib`假定它是一个`y`值序列,并自动为你生成`x`值。 由于 python 范围从 0 开始,默认`x`向量具有与`y`相同的长度,但从 0 开始。因此`x`数据是`[0,1,2,3]`。 21 | 22 | `plot()`是一个通用命令,并且可接受任意数量的参数。 例如,要绘制`x`和`y`,你可以执行命令: 23 | 24 | ```py 25 | plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) 26 | ``` 27 | 28 | 对于每个`x,y`参数对,有一个可选的第三个参数,它是指示图形颜色和线条类型的格式字符串。 格式字符串的字母和符号来自 MATLAB,并且将颜色字符串与线型字符串连接在一起。 默认格式字符串为`"b-"`,它是一条蓝色实线。 例如,要绘制上面的红色圆圈,你需要执行: 29 | 30 | ```py 31 | import matplotlib.pyplot as plt 32 | plt.plot([1,2,3,4], [1,4,9,16], 'ro') 33 | plt.axis([0, 6, 0, 20]) 34 | plt.show() 35 | ``` 36 | 37 | ![](http://matplotlib.org/_images/pyplot_formatstr.png) 38 | 39 | 有关线型和格式字符串的完整列表,请参见[`plot()`文档](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot)。 上例中的`axis()`命令接收`[xmin,xmax,ymin,ymax]`的列表,并指定轴域的可视区域。 40 | 41 | 如果`matplotlib`仅限于使用列表,它对于数字处理是相当无用的。 一般来说,你可以使用`numpy`数组。 事实上,所有序列都在内部转换为`numpy`数组。 下面的示例展示了使用数组和不同格式字符串,在一条命令中绘制多个线条。 42 | 43 | ```py 44 | import numpy as np 45 | import matplotlib.pyplot as plt 46 | 47 | # evenly sampled time at 200ms intervals 48 | t = np.arange(0., 5., 0.2) 49 | 50 | # red dashes, blue squares and green triangles 51 | plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') 52 | plt.show() 53 | ``` 54 | 55 | ![](http://matplotlib.org/_images/pyplot_three.png) 56 | 57 | ## 控制线条属性 58 | 59 | 线条有许多你可以设置的属性:`linewidth`,`dash style`,`antialiased`等,请参见`matplotlib.lines.Line2D`。 有几种方法可以设置线属性: 60 | 61 | + 使用关键字参数: 62 | 63 | ```py 64 | plt.plot(x, y, linewidth=2.0) 65 | ``` 66 | 67 | + 使用`Line2D`实例的`setter`方法。 `plot`返回`Line2D`对象的列表,例如`line1,line2 = plot(x1,y1,x2,y2)`。 在下面的代码中,我们假设只有一行,返回的列表长度为 1。我们对`line`使用元组解构,得到该列表的第一个元素: 68 | 69 | ```py 70 | line, = plt.plot(x, y, '-') 71 | line.set_antialiased(False) # turn off antialising 72 | ``` 73 | 74 | + 使用`setp()`命令。 下面的示例使用 MATLAB 风格的命令来设置线条列表上的多个属性。 `setp`使用对象列表或单个对象透明地工作。 你可以使用 python 关键字参数或 MATLAB 风格的字符串/值对: 75 | 76 | ```py 77 | lines = plt.plot(x1, y1, x2, y2) 78 | # 使用关键字参数 79 | plt.setp(lines, color='r', linewidth=2.0) 80 | # 或者 MATLAB 风格的字符串值对 81 | plt.setp(lines, 'color', 'r', 'linewidth', 2.0) 82 | ``` 83 | 84 | 下面是可用的`Line2D`属性。 85 | 86 | 87 | | 属性 | 值类型 | 88 | | --- | --- | 89 | | `alpha` | 浮点值 | 90 | | `animated` | `[True / False]` | 91 | | `antialiased or aa` | `[True / False]` | 92 | | `clip_box` | `matplotlib.transform.Bbox` 实例 | 93 | | `clip_on` | `[True / False]` | 94 | | `clip_path` | `Path` 实例, `Transform`,以及`Patch`实例 | 95 | | `color or c` | 任何 `matplotlib` 颜色 | 96 | | `contains` | 命中测试函数 | 97 | | `dash_capstyle` | `['butt' / 'round' / 'projecting']` | 98 | | `dash_joinstyle` | `['miter' / 'round' / 'bevel']` | 99 | | `dashes` | 以点为单位的连接/断开墨水序列 | 100 | | `data` | `(np.array xdata, np.array ydata)` | 101 | | `figure` | `matplotlib.figure.Figure` 实例 | 102 | | `label` | 任何字符串 | 103 | | `linestyle` or `ls` | `[ '-' / '--' / '-.' / ':' / 'steps' / ...]` | 104 | | `linewidth` or `lw` | 以点为单位的浮点值 | 105 | | `lod` | `[True / False]` | 106 | | `marker` | `[ '+' / ',' / '.' / '1' / '2' / '3' / '4' ]` | 107 | | `markeredgecolor or mec` | 任何 `matplotlib` 颜色 | 108 | | `markeredgewidth or mew` | 以点为单位的浮点值 | 109 | | `markerfacecolor or mfc` | 任何 `matplotlib` 颜色 | 110 | | `markersize or ms` | 浮点值 | 111 | | `markevery` | `[ None / 整数值 / (startind, stride) ]` | 112 | | `picker` | 用于交互式线条选择 | 113 | | `pickradius` | 线条的拾取选择半径 | 114 | | `solid_capstyle` | `['butt' / 'round' / 'projecting']` | 115 | | `solid_joinstyle` | `['miter' / 'round' / 'bevel']` | 116 | | `transform` | `matplotlib.transforms.Transform` 实例 | 117 | | `visible` | `[True / False]` | 118 | | `xdata` | `np.array` | 119 | | `ydata` | `np.array` | 120 | | `zorder` | 任何数值 | 121 | 122 | 要获取可设置的线条属性的列表,请以一个或多个线条作为参数调用`step()`函数 123 | 124 | ```py 125 | In [69]: lines = plt.plot([1, 2, 3]) 126 | 127 | In [70]: plt.setp(lines) 128 | alpha: float 129 | animated: [True | False] 130 | antialiased or aa: [True | False] 131 | ...snip 132 | ``` 133 | 134 | ## 处理多个图形和轴域 135 | 136 | MATLAB 和 pyplot 具有当前图形和当前轴域的概念。 所有绘图命令适用于当前轴域。 函数`gca()`返回当前轴域(一个`matplotlib.axes.Axes`实例),`gcf()`返回当前图形(`matplotlib.figure.Figure`实例)。 通常,你不必担心这一点,因为它都是在幕后处理。 下面是一个创建两个子图的脚本。 137 | 138 | ```py 139 | import numpy as np 140 | import matplotlib.pyplot as plt 141 | 142 | def f(t): 143 | return np.exp(-t) * np.cos(2*np.pi*t) 144 | 145 | t1 = np.arange(0.0, 5.0, 0.1) 146 | t2 = np.arange(0.0, 5.0, 0.02) 147 | 148 | plt.figure(1) 149 | plt.subplot(211) 150 | plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') 151 | 152 | plt.subplot(212) 153 | plt.plot(t2, np.cos(2*np.pi*t2), 'r--') 154 | plt.show() 155 | ``` 156 | 157 | ![](http://matplotlib.org/_images/pyplot_two_subplots.png) 158 | 159 | 这里的`figure()`命令是可选的,因为默认情况下将创建`figure(1)`,如果不手动指定任何轴域,则默认创建`subplot(111)`。`subplot()`命令指定`numrows`,`numcols`,`fignum`,其中`fignum`的范围是从`1`到`numrows * numcols`。 如果`numrows * numcols <10`,则`subplot`命令中的逗号是可选的。 因此,子图`subplot(211)`与`subplot(2, 1, 1)`相同。 你可以创建任意数量的子图和轴域。 如果要手动放置轴域,即不在矩形网格上,请使用`axes()`命令,该命令允许你将`axes([left, bottom, width, height])`指定为位置,其中所有值都使用小数(0 到 1)坐标。 手动放置轴域的示例请参见[`pylab_examples`示例代码:`axes_demo.py`](http://matplotlib.org/examples/pylab_examples/axes_demo.html#pylab-examples-axes-demo),具有大量子图的示例请参见[`pylab_examples`示例代码:`subplots_demo.py`](http://matplotlib.org/examples/pylab_examples/subplots_demo.html#pylab-examples-subplots-demo)。 160 | 161 | 你可以通过使用递增图形编号多次调用`figure()`来创建多个图形。 当然,每个数字可以包含所需的轴和子图数量: 162 | 163 | ```py 164 | import matplotlib.pyplot as plt 165 | plt.figure(1) # 第一个图形 166 | plt.subplot(211) # 第一个图形的第一个子图 167 | plt.plot([1, 2, 3]) 168 | plt.subplot(212) # 第一个图形的第二个子图 169 | plt.plot([4, 5, 6]) 170 | 171 | 172 | plt.figure(2) # 第二个图形 173 | plt.plot([4, 5, 6]) # 默认创建 subplot(111) 174 | 175 | plt.figure(1) # 当前是图形 1,subplot(212) 176 | plt.subplot(211) # 将第一个图形的 subplot(211) 设为当前子图 177 | plt.title('Easy as 1, 2, 3') # 子图 211 的标题 178 | ``` 179 | 180 | 你可以使用`clf()`清除当前图形,使用`cla()`清除当前轴域。 如果你搞不清在幕后维护的状态(特别是当前的图形和轴域),不要绝望:这只是一个面向对象的 API 的简单的状态包装器,你可以使用面向对象 API(见[艺术家教程](http://matplotlib.org/users/artists.html#artist-tutorial))。 181 | 182 | 如果你正在制作大量的图形,你需要注意一件事:在一个图形用`close()`显式关闭之前,该图所需的内存不会完全释放。 删除对图形的所有引用,和/或使用窗口管理器杀死屏幕上出现的图形的窗口是不够的,因为在调用`close()`之前,`pyplot`会维护内部引用。 183 | 184 | ## 处理文本 185 | 186 | `text()`命令可用于在任意位置添加文本,`xlabel()`,`ylabel()`和`title()`用于在指定的位置添加文本(详细示例请参阅[文本介绍](http://matplotlib.org/users/text_intro.html#text-intro))。 187 | 188 | ```py 189 | import numpy as np 190 | import matplotlib.pyplot as plt 191 | 192 | mu, sigma = 100, 15 193 | x = mu + sigma * np.random.randn(10000) 194 | 195 | # 数据的直方图 196 | n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) 197 | 198 | 199 | plt.xlabel('Smarts') 200 | plt.ylabel('Probability') 201 | plt.title('Histogram of IQ') 202 | plt.text(60, .025, r'$\mu=100,\ \sigma=15$') 203 | plt.axis([40, 160, 0, 0.03]) 204 | plt.grid(True) 205 | plt.show() 206 | ``` 207 | 208 | ![](http://matplotlib.org/_images/pyplot_text.png) 209 | 210 | 所有的`text()`命令返回一个`matplotlib.text.Text`实例。 与上面一样,你可以通过将关键字参数传递到`text`函数或使用`setp()`来自定义属性: 211 | 212 | ```py 213 | t = plt.xlabel('my data', fontsize=14, color='red') 214 | ``` 215 | 216 | 这些属性的更详细介绍请见[文本属性和布局](http://matplotlib.org/users/text_props.html#text-properties)。 217 | 218 | 219 | ## 在文本中使用数学表达式 220 | 221 | `matplotlib`在任何文本表达式中接受 TeX 方程表达式。 例如,要在标题中写入表达式,可以编写一个由美元符号包围的 TeX 表达式: 222 | 223 | ```py 224 | plt.title(r'$\sigma_i=15$') 225 | ``` 226 | 227 | 标题字符串之前的`r`很重要 - 它表示该字符串是一个原始字符串,而不是将反斜杠作为 python 转义处理。 `matplotlib`有一个内置的 TeX 表达式解析器和布局引擎,并且自带了自己的数学字体 - 详细信息请参阅[编写数学表达式](http://matplotlib.org/users/mathtext.html#mathtext-tutorial)。 因此,你可以跨平台使用数学文本,而无需安装 TeX。 对于安装了 LaTeX 和`dvipng`的用户,还可以使用 LaTeX 格式化文本,并将输出直接合并到显示图形或保存的 postscript 中 - 请参阅[使用 LaTeX 进行文本渲染](http://matplotlib.org/users/usetex.html#usetex-tutorial)。 228 | 229 | ## 标注文本 230 | 231 | 上面的`text()`基本命令将文本放置在轴域的任意位置。 文本的一个常见用法是对图的某些特征执行标注,而`annotate()`方法提供一些辅助功能,使标注变得容易。 在标注中,有两个要考虑的点:由参数`xy`表示的标注位置和`xytext`表示的文本位置。 这两个参数都是`(x, y)`元组。 232 | 233 | ![](http://matplotlib.org/_images/pyplot_annotate.png) 234 | 235 | 236 | 在此基本示例中,`xy`(箭头提示)和`xytext`(文本)都位于数据坐标中。 有多种其他坐标系可供选择 - 详细信息请参阅[标注文本](http://matplotlib.org/users/annotations_intro.html#annotations-tutorial)和[标注轴域](http://matplotlib.org/users/annotations_guide.html#plotting-guide-annotation)。 更多示例可以在[`pylab_examples`示例代码:`annotation_demo.py`](http://matplotlib.org/examples/pylab_examples/annotation_demo.html#pylab-examples-annotation-demo)中找到。 237 | 238 | ## 对数和其它非线性轴 239 | 240 | `matplotlib.pyplot`不仅支持线性轴刻度,还支持对数和对数刻度。 如果数据跨越许多数量级,通常会使用它。 更改轴的刻度很容易: 241 | 242 | ```py 243 | plt.xscale('log') 244 | ``` 245 | 246 | 下面示例显示了四个图,具有相同数据和不同刻度的`y`轴。 247 | 248 | ```py 249 | import numpy as np 250 | import matplotlib.pyplot as plt 251 | 252 | # 生成一些区间 [0, 1] 内的数据 253 | y = np.random.normal(loc=0.5, scale=0.4, size=1000) 254 | y = y[(y > 0) & (y < 1)] 255 | y.sort() 256 | x = np.arange(len(y)) 257 | 258 | # 带有多个轴域刻度的 plot 259 | plt.figure(1) 260 | 261 | # 线性 262 | plt.subplot(221) 263 | plt.plot(x, y) 264 | plt.yscale('linear') 265 | plt.title('linear') 266 | plt.grid(True) 267 | 268 | 269 | # 对数 270 | plt.subplot(222) 271 | plt.plot(x, y) 272 | plt.yscale('log') 273 | plt.title('log') 274 | plt.grid(True) 275 | 276 | 277 | # 对称的对数 278 | plt.subplot(223) 279 | plt.plot(x, y - y.mean()) 280 | plt.yscale('symlog', linthreshy=0.05) 281 | plt.title('symlog') 282 | plt.grid(True) 283 | 284 | # logit 285 | plt.subplot(224) 286 | plt.plot(x, y) 287 | plt.yscale('logit') 288 | plt.title('logit') 289 | plt.grid(True) 290 | 291 | plt.show() 292 | ``` 293 | 294 | ![](http://matplotlib.org/_images/pyplot_scales.png) 295 | 296 | 还可以添加自己的刻度,详细信息请参阅[向`matplotlib`添加新的刻度和投影](http://matplotlib.org/devel/add_new_projection.html#adding-new-scales)。 297 | -------------------------------------------------------------------------------- /3.2.md: -------------------------------------------------------------------------------- 1 | # 图像教程 2 | 3 | > 原文:[Image tutorial](http://matplotlib.org/users/image_tutorial.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | ## 启动命令 10 | 11 | 首先,让我们启动 IPython。 它是 Python 标准提示符的最好的改进,它与 Matplotlib 配合得相当不错。 在 shell 或 IPython Notebook 上都可以启动 IPython。 12 | 13 | 随着 IPython 启动,我们现在需要连接到 GUI 事件循环。 它告诉 IPython 在哪里(以及如何显示)绘图。 要连接到 GUI 循环,请在 IPython 提示符处执行`%matplotlib`魔法。 在 [IPython 的 GUI 事件循环文档](http://ipython.org/ipython-doc/2/interactive/reference.html#gui-event-loop-support)中有更多的细节。 14 | 15 | 如果使用 IPython Notebook,可以使用相同的命令,但人们通常以特定参数使用`%matplotlib`: 16 | 17 | ``` 18 | In [1]: %matplotlib inline 19 | ``` 20 | 21 | 这将打开内联绘图,绘图图形将显示在笔记本中。 这对交互性有很重要的影响。 对于内联绘图,在单元格下方的单元格中输出绘图的命令不会影响绘图。 例如,从创建绘图的单元格下面的单元格更改颜色表是不可能的。 但是,对于其他后端,例如 qt4,它们会打开一个单独的窗口,那些创建绘图的单元格下方的单元格将改变绘图 - 它是一个内存中的活对象。 22 | 23 | 本教程将使用`matplotlib`的命令式绘图接口`pyplot`。 该接口维护全局状态,并且可用于简单快速地尝试各种绘图设置。 另一种是面向对象的接口,这也非常强大,一般更适合大型应用程序的开发。 如果你想了解面向对象接口,[使用上的常见问题](http://matplotlib.org/faq/usage_faq.html)是一个用于起步的不错的页面。 现在,让我们继续使用命令式方式: 24 | 25 | ```py 26 | In [2]: import matplotlib.pyplot as plt 27 | In [3]: import matplotlib.image as mpimg 28 | In [4]: import numpy as np 29 | ``` 30 | 31 | ## 将图像数据导入到 NumPy 数组 32 | 33 | 加载图像数据由 Pillow 库提供支持。 本来,`matplotlib`只支持 PNG 图像。 如果本机读取失败,下面显示的命令会回退到 Pillow。 34 | 35 | 此示例中使用的图像是 PNG 文件,但是请记住你自己的数据的 Pillow 要求。 36 | 37 | 下面是我们要摆弄的图片: 38 | 39 | ![](http://matplotlib.org/_images/stinkbug.png) 40 | 41 | 它是一个 24 位 RGB PNG 图像(每个 R,G,B 为 8 位)。 根据你获取数据的位置,你最有可能遇到的其他类型的图像是 RGBA 图像,拥有透明度或单通道灰度(亮度)的图像。 你可以右键单击它,选择`Save image as`(另存为)为本教程的剩余部分下载到你的计算机。 42 | 43 | 现在我们开始... 44 | 45 | ```py 46 | In [5]: img=mpimg.imread('stinkbug.png') 47 | Out[5]: 48 | array([[[ 0.40784314, 0.40784314, 0.40784314], 49 | [ 0.40784314, 0.40784314, 0.40784314], 50 | [ 0.40784314, 0.40784314, 0.40784314], 51 | ..., 52 | [ 0.42745098, 0.42745098, 0.42745098], 53 | [ 0.42745098, 0.42745098, 0.42745098], 54 | [ 0.42745098, 0.42745098, 0.42745098]], 55 | 56 | ..., 57 | [[ 0.44313726, 0.44313726, 0.44313726], 58 | [ 0.4509804 , 0.4509804 , 0.4509804 ], 59 | [ 0.4509804 , 0.4509804 , 0.4509804 ], 60 | ..., 61 | [ 0.44705883, 0.44705883, 0.44705883], 62 | [ 0.44705883, 0.44705883, 0.44705883], 63 | [ 0.44313726, 0.44313726, 0.44313726]]], dtype=float32) 64 | ``` 65 | 66 | 注意这里的`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)。 67 | 68 | 每个内部列表表示一个像素。 这里,对于 RGB 图像,有 3 个值。 由于它是一个黑白图像,R,G 和 B 都是类似的。 RGBA(其中 A 是阿尔法或透明度)对于每个内部列表具有 4 个值,而且简单亮度图像仅具有一个值(因此仅是二维数组,而不是三维数组)。 对于 RGB 和 RGBA 图像,`matplotlib`支持`float32`和`uint8`数据类型。 对于灰度,`matplotlib`只支持`float32`。 如果你的数组数据不符合这些描述之一,则需要重新缩放它。 69 | 70 | ## 将 NumPy 数组绘制为图像 71 | 72 | 所以,你将数据保存在一个`numpy`数组(通过导入它,或生成它)。 让我们渲染它吧。 在 Matplotlib 中,这是使用`imshow()`函数执行的。 这里我们将抓取`plot`对象。 这个对象提供了一个简单的方法来从提示符处理绘图。 73 | 74 | ```py 75 | In [6]: imgplot = plt.imshow(img) 76 | ``` 77 | 78 | ![](http://matplotlib.org/_images/image_tutorial-1.png) 79 | 80 | 你也可以绘制任何 NumPy 数组。 81 | 82 | ### 对图像绘图应用伪彩色方案 83 | 84 | 伪彩色可以是一个有用的工具,用于增强对比度和更易于可视化你的数据。 这在使用投影仪对你的数据进行演示时尤其有用 - 它们的对比度通常很差。 85 | 86 | 伪彩色仅与单通道,灰度,亮度图像相关。 我们目前有一个RGB图像。 由于R,G 和 B 都是相似的(见上面或你的数据),我们可以只选择一个通道的数据: 87 | 88 | ```py 89 | In [7]: lum_img = img[:,:,0] 90 | ``` 91 | 92 | 这是数组切片,更多信息请见[NumPy 教程](http://www.scipy.org/Tentative_NumPy_Tutorial)。 93 | 94 | ```py 95 | In [8]: plt.imshow(lum_img) 96 | ``` 97 | 98 | ![](http://matplotlib.org/_images/image_tutorial-2.png) 99 | 100 | 现在,亮度(2D,无颜色)图像应用了默认颜色表(也称为查找表,LUT)。 默认值称为`jet`。 有很多其他方案可以选择。 101 | 102 | ```py 103 | In [9]: plt.imshow(lum_img, cmap="hot") 104 | ``` 105 | 106 | ![](http://matplotlib.org/_images/image_tutorial-3.png) 107 | 108 | 109 | 请注意,你还可以使用`set_cmap()`方法更改现有绘图对象上的颜色: 110 | 111 | ```py 112 | In [10]: imgplot = plt.imshow(lum_img) 113 | In [11]: imgplot.set_cmap('spectral') 114 | ``` 115 | 116 | ![](http://matplotlib.org/_images/image_tutorial-4.png) 117 | 118 | > 注 119 | 120 | > 但是,请记住,在带有内联后端的 IPython notebook 中,你不能对已经渲染的绘图进行更改。 如果你在一个单元格中创建了`imgplot`,你不能在以后的单元格中调用`set_cmap()`,并且改变前面的绘图。 请确保你在相同单元格中一起输入这些命令。`plt`命令不会更改先前单元格的绘图。 121 | 122 | 有许多可选的其它颜色表,请见[颜色表的列表和图像](http://matplotlib.org/examples/color/colormaps_reference.html)。 123 | 124 | ### 颜色刻度参考 125 | 126 | 了解颜色代表什么值对我们很有帮助。 我们可以通过添加颜色条来做到这一点。 127 | 128 | ```py 129 | In [12]: imgplot = plt.imshow(lum_img) 130 | In [13]: plt.colorbar() 131 | ``` 132 | 133 | ![](http://matplotlib.org/_images/image_tutorial-5.png) 134 | 135 | 这会为你现有的图形添加一个颜色条。 如果你更改并切换到不同的颜色映射,则不会自动更改 - 你必须重新创建绘图,并再次添加颜色条。 136 | 137 | ### 检查特定数据范围 138 | 139 | 有时,你想要增强图像的对比度,或者扩大特定区域的对比度,同时牺牲变化不大,或者无所谓的颜色细节。 找到有趣区域的最好工具是直方图。 要创建我们的图像数据的直方图,我们使用`hist()`函数。 140 | 141 | ```py 142 | In [14]: plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k') 143 | ``` 144 | 145 | ![](http://matplotlib.org/_images/image_tutorial-6.png) 146 | 147 | 通常,图像的『有趣』部分在峰值附近,你可以通过剪切峰值上方和/或下方的区域获得额外的对比度。 在我们的直方图中,看起来最大值处没有太多有用的信息(图像中有很多不是白色的东西)。 让我们调整上限,以便我们有效地『放大』直方图的一部分。 我们通过将`clim`参数传递给`imshow`来实现。 你也可以通过对图像绘图对象调用`set_clim()`方法来做到这一点,但要确保你在使用 IPython Notebook 的时候,和`plot`命令在相同的单元格中执行 - 它不会改变之前单元格的图。 148 | 149 | ```py 150 | In [15]: imgplot = plt.imshow(lum_img, clim=(0.0, 0.7)) 151 | ``` 152 | 153 | ![](http://matplotlib.org/_images/image_tutorial-7.png) 154 | 155 | ### 数组插值方案 156 | 157 | 插值根据不同的数学方案计算像素『应有』的颜色或值。 发生这种情况的一个常见的场景是调整图像的大小。 像素的数量会发生变化,但你想要相同的信息。 由于像素是离散的,因此存在缺失的空间。 插值就是填补这个空间的方式。 这就是当你放大图像时,你的图像有时会出来看起来像素化的原因。 当原始图像和扩展图像之间的差异较大时,效果更加明显。 让我们加载我们的图像并缩小它。 我们实际上正在丢弃像素,只保留少数几个像素。 现在,当我们绘制它时,数据被放大为你屏幕的大小。 由于旧的像素不再存在,计算机必须绘制像素来填充那个空间。 158 | 159 | 我们将使用用来加载图像的 Pillow 库来调整图像大小。 160 | 161 | ```py 162 | In [16]: from PIL import Image 163 | In [17]: img = Image.open('../_static/stinkbug.png') 164 | In [18]: img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place 165 | In [19]: imgplot = plt.imshow(img) 166 | ``` 167 | 168 | ![](http://matplotlib.org/_images/image_tutorial-8.png) 169 | 170 | 这里我们使用默认插值,双线性,因为我们没有向`imshow()`提供任何插值参数。 171 | 172 | 让我们试试一些其它的东西: 173 | 174 | 最邻近 175 | 176 | ```py 177 | In [20]: imgplot = plt.imshow(img, interpolation="nearest") 178 | ``` 179 | 180 | ![](http://matplotlib.org/_images/image_tutorial-9.png) 181 | 182 | 双立方 183 | 184 | ```py 185 | In [21]: imgplot = plt.imshow(img, interpolation="bicubic") 186 | ``` 187 | 188 | ![](http://matplotlib.org/_images/image_tutorial-10.png) 189 | 190 | 双立方插值通常用于放大照片 - 人们倾向于模糊而不是过度像素化。 191 | -------------------------------------------------------------------------------- /3.3.md: -------------------------------------------------------------------------------- 1 | # 使用 GridSpec 自定义子图位置 2 | 3 | > 原文:[Customizing Location of Subplot Using GridSpec](http://matplotlib.org/users/gridspec.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | `GridSpec` 10 | 11 | 指定子图将放置的网格的几何位置。 需要设置网格的行数和列数。 子图布局参数(例如,左,右等)可以选择性调整。 12 | 13 | `SubplotSpec` 14 | 15 | 指定在给定`GridSpec`中的子图位置。 16 | 17 | `subplot2grid` 18 | 19 | 一个辅助函数,类似于`pyplot.subplot`,但是使用基于 0 的索引,并可使子图跨越多个格子。 20 | 21 | ## `subplot2grid`基本示例 22 | 23 | 要使用subplot2grid,你需要提供网格的几何形状和网格中子图的位置。 对于简单的单网格子图: 24 | 25 | ```py 26 | ax = plt.subplot2grid((2,2),(0, 0)) 27 | ``` 28 | 29 | 等价于: 30 | 31 | ``` 32 | ax = plt.subplot(2,2,1) 33 | ``` 34 | 35 | ``` 36 | nRow=2, nCol=2 37 | (0,0) +-------+-------+ 38 | | 1 | | 39 | +-------+-------+ 40 | | | | 41 | +-------+-------+ 42 | ``` 43 | 44 | 要注意不想`subplot`,`gridspec`中的下标从 0 开始。 45 | 46 | 为了创建跨越多个格子的子图, 47 | 48 | ```py 49 | ax2 = plt.subplot2grid((3,3), (1, 0), colspan=2) 50 | ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2) 51 | ``` 52 | 53 | 例如,下列命令: 54 | 55 | ```py 56 | ax1 = plt.subplot2grid((3,3), (0,0), colspan=3) 57 | ax2 = plt.subplot2grid((3,3), (1,0), colspan=2) 58 | ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2) 59 | ax4 = plt.subplot2grid((3,3), (2, 0)) 60 | ax5 = plt.subplot2grid((3,3), (2, 1)) 61 | ``` 62 | 63 | 会创建: 64 | 65 | ![](http://matplotlib.org/_images/demo_gridspec01.png) 66 | 67 | ## `GridSpec`和`SubplotSpec` 68 | 69 | 你可以显式创建`GridSpec `并用它们创建子图。 70 | 71 | 例如, 72 | 73 | ```py 74 | ax = plt.subplot2grid((2,2),(0, 0)) 75 | ``` 76 | 77 | 等价于: 78 | 79 | ```py 80 | import matplotlib.gridspec as gridspec 81 | gs = gridspec.GridSpec(2, 2) 82 | ax = plt.subplot(gs[0, 0]) 83 | ``` 84 | 85 | `gridspec `示例提供类似数组(一维或二维)的索引,并返回`SubplotSpec`实例。例如,使用切片来返回跨越多个格子的`SubplotSpec`实例。 86 | 87 | 上面的例子会变成: 88 | 89 | ```py 90 | gs = gridspec.GridSpec(3, 3) 91 | ax1 = plt.subplot(gs[0, :]) 92 | ax2 = plt.subplot(gs[1,:-1]) 93 | ax3 = plt.subplot(gs[1:, -1]) 94 | ax4 = plt.subplot(gs[-1,0]) 95 | ax5 = plt.subplot(gs[-1,-2]) 96 | ``` 97 | 98 | ![](http://matplotlib.org/_images/demo_gridspec02.png) 99 | 100 | ## 调整 `GridSpec`布局 101 | 102 | 在显式使用`GridSpec`的时候,你可以调整子图的布局参数,子图由`gridspec`创建。 103 | 104 | ```py 105 | gs1 = gridspec.GridSpec(3, 3) 106 | gs1.update(left=0.05, right=0.48, wspace=0.05) 107 | ``` 108 | 109 | 这类似于`subplots_adjust`,但是他只影响从给定`GridSpec`创建的子图。 110 | 111 | 下面的代码 112 | 113 | ```py 114 | gs1 = gridspec.GridSpec(3, 3) 115 | gs1.update(left=0.05, right=0.48, wspace=0.05) 116 | ax1 = plt.subplot(gs1[:-1, :]) 117 | ax2 = plt.subplot(gs1[-1, :-1]) 118 | ax3 = plt.subplot(gs1[-1, -1]) 119 | 120 | gs2 = gridspec.GridSpec(3, 3) 121 | gs2.update(left=0.55, right=0.98, hspace=0.05) 122 | ax4 = plt.subplot(gs2[:, :-1]) 123 | ax5 = plt.subplot(gs2[:-1, -1]) 124 | ax6 = plt.subplot(gs2[-1, -1]) 125 | ``` 126 | 127 | 会产生 128 | 129 | ![](http://matplotlib.org/_images/demo_gridspec03.png) 130 | 131 | ## 使用 `SubplotSpec`创建 `GridSpec` 132 | 133 | 你可以从`SubplotSpec`创建`GridSpec`,其中它的布局参数设置为给定`SubplotSpec`的位置的布局参数。 134 | 135 | ```py 136 | gs0 = gridspec.GridSpec(1, 2) 137 | 138 | gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0]) 139 | gs01 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[1]) 140 | ``` 141 | 142 | ![](http://matplotlib.org/_images/demo_gridspec04.png) 143 | 144 | ## 使用`SubplotSpec`创建复杂嵌套的`GridSpec` 145 | 146 | 这里有一个更复杂的嵌套`gridspec`的示例,我们通过在每个 3x3 内部网格中隐藏适当的脊线,在 4x4 外部网格的每个单元格周围放置一个框。 147 | 148 | ![](http://matplotlib.org/_images/demo_gridspec06.png) 149 | 150 | ## 网格尺寸可变的`GridSpec` 151 | 152 | 通常,`GridSpec`创建大小相等的网格。你可以调整行和列的相对高度和宽度,要注意绝对高度值是无意义的,有意义的只是它们的相对比值。 153 | 154 | ```py 155 | gs = gridspec.GridSpec(2, 2, 156 | width_ratios=[1,2], 157 | height_ratios=[4,1] 158 | ) 159 | 160 | ax1 = plt.subplot(gs[0]) 161 | ax2 = plt.subplot(gs[1]) 162 | ax3 = plt.subplot(gs[2]) 163 | ax4 = plt.subplot(gs[3]) 164 | ``` 165 | 166 | ![](http://matplotlib.org/_images/demo_gridspec05.png) 167 | -------------------------------------------------------------------------------- /3.4.md: -------------------------------------------------------------------------------- 1 | # 密致布局指南 2 | 3 | > 原文:[Tight Layout guide](http://matplotlib.org/users/tight_layout_guide.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | `tight_layout`会自动调整子图参数,使之填充整个图像区域。这是个实验特性,可能在一些情况下不工作。它仅仅检查坐标轴标签、刻度标签以及标题的部分。 10 | 11 | ## 简单的示例 12 | 13 | 在 matplotlib 中,轴域(包括子图)的位置以标准化图形坐标指定。 可能发生的是,你的轴标签或标题(有时甚至是刻度标签)会超出图形区域,因此被截断。 14 | 15 | ```py 16 | plt.rcParams['savefig.facecolor'] = "0.8" 17 | 18 | def example_plot(ax, fontsize=12): 19 | ax.plot([1, 2]) 20 | ax.locator_params(nbins=3) 21 | ax.set_xlabel('x-label', fontsize=fontsize) 22 | ax.set_ylabel('y-label', fontsize=fontsize) 23 | ax.set_title('Title', fontsize=fontsize) 24 | 25 | plt.close('all') 26 | fig, ax = plt.subplots() 27 | example_plot(ax, fontsize=24) 28 | ``` 29 | 30 | ![](http://matplotlib.org/_images/tight_layout_guide-1.png) 31 | 32 | 为了避免它,轴域的位置需要调整。对于子图,这可以通过调整子图参数([移动轴域的一条边来给刻度标签腾地方](http://matplotlib.org/faq/howto_faq.html#howto-subplots-adjust))。Matplotlib v1.1 引入了一个新的命令` tight_layout()`,自动为你解决这个问题。 33 | 34 | ```py 35 | plt.tight_layout() 36 | ``` 37 | 38 | ![](http://matplotlib.org/_images/tight_layout_guide-2.png) 39 | 40 | 当你拥有多个子图时,你会经常看到不同轴域的标签叠在一起。 41 | 42 | ```py 43 | plt.close('all') 44 | fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) 45 | example_plot(ax1) 46 | example_plot(ax2) 47 | example_plot(ax3) 48 | example_plot(ax4) 49 | ``` 50 | 51 | ![](http://matplotlib.org/_images/tight_layout_guide-3.png) 52 | 53 | `tight_layout()`也会调整子图之间的间隔来减少堆叠。 54 | 55 | ![](http://matplotlib.org/_images/tight_layout_guide-4.png) 56 | 57 | `tight_layout()`可以接受关键字参数`pad`、`w_pad`或者`h_pad`,这些参数图像边界和子图之间的额外边距。边距以字体大小单位规定。 58 | 59 | ```py 60 | plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) 61 | ``` 62 | 63 | ![](http://matplotlib.org/_images/tight_layout_guide-5.png) 64 | 65 | 即使子图大小不同,`tight_layout()`也能够工作,只要网格的规定的兼容的。在下面的例子中,`ax1`和`ax2`是 2x2 网格的子图,但是`ax3`是 1x2 网格。 66 | 67 | ```py 68 | plt.close('all') 69 | fig = plt.figure() 70 | 71 | ax1 = plt.subplot(221) 72 | ax2 = plt.subplot(223) 73 | ax3 = plt.subplot(122) 74 | 75 | example_plot(ax1) 76 | example_plot(ax2) 77 | example_plot(ax3) 78 | 79 | plt.tight_layout() 80 | ``` 81 | 82 | ![](http://matplotlib.org/_images/tight_layout_guide-6.png) 83 | 84 | 它适用于使用`subplot2grid()`创建的子图。 一般来说,从`gridspec`([使用`GridSpec`自定义子布局的位置](http://matplotlib.org/users/gridspec.html#gridspec-guide))创建的子图也能正常工作。 85 | 86 | ```py 87 | plt.close('all') 88 | fig = plt.figure() 89 | 90 | ax1 = plt.subplot2grid((3, 3), (0, 0)) 91 | ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) 92 | ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) 93 | ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) 94 | 95 | example_plot(ax1) 96 | example_plot(ax2) 97 | example_plot(ax3) 98 | example_plot(ax4) 99 | 100 | plt.tight_layout() 101 | ``` 102 | 103 | ![](http://matplotlib.org/_images/tight_layout_guide-7.png) 104 | 105 | 虽然没有彻底测试,它看起来也适用于`aspect`不为`auto`的子图(例如带有图像的轴域)。 106 | 107 | ```py 108 | arr = np.arange(100).reshape((10,10)) 109 | 110 | plt.close('all') 111 | fig = plt.figure(figsize=(5,4)) 112 | 113 | ax = plt.subplot(111) 114 | im = ax.imshow(arr, interpolation="none") 115 | 116 | plt.tight_layout() 117 | ``` 118 | 119 | ![](http://matplotlib.org/_images/tight_layout_guide-8.png) 120 | 121 | ## 警告 122 | 123 | + `tight_layout()`只考虑刻度标签,轴标签和标题。 因此,其他艺术家可能被截断并且也可能重叠。 124 | + 它假定刻度标签,轴标签和标题所需的额外空间与轴域的原始位置无关。 这通常是真的,但在罕见的情况下不是。 125 | + `pad = 0`将某些文本剪切几个像素。 这可能是当前算法的错误或限制,并且不清楚为什么会发生。 同时,推荐使用至少大于 0.3 的间隔。 126 | 127 | ## 和`GridSpec`一起使用 128 | 129 | `GridSpec`拥有自己的`tight_layout()`方法(pyplot API 的`tight_layout()`也能生效)。 130 | 131 | ```py 132 | 133 | plt.close('all') 134 | fig = plt.figure() 135 | 136 | import matplotlib.gridspec as gridspec 137 | 138 | gs1 = gridspec.GridSpec(2, 1) 139 | ax1 = fig.add_subplot(gs1[0]) 140 | ax2 = fig.add_subplot(gs1[1]) 141 | 142 | example_plot(ax1) 143 | example_plot(ax2) 144 | 145 | gs1.tight_layout(fig) 146 | ``` 147 | 148 | ![](http://matplotlib.org/_images/tight_layout_guide-9.png) 149 | 150 | 你可以提供一个可选的`rect`参数,指定子图所填充的边框。 坐标必须为标准化图形坐标,默认值为`(0, 0, 1, 1)`。 151 | 152 | ```py 153 | gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) 154 | ``` 155 | 156 | ![](http://matplotlib.org/_images/tight_layout_guide-10.png) 157 | 158 | 例如,这可用于带有多个`gridspecs`的图形。 159 | 160 | ```py 161 | gs2 = gridspec.GridSpec(3, 1) 162 | 163 | for ss in gs2: 164 | ax = fig.add_subplot(ss) 165 | example_plot(ax) 166 | ax.set_title("") 167 | ax.set_xlabel("") 168 | 169 | ax.set_xlabel("x-label", fontsize=12) 170 | 171 | gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) 172 | ``` 173 | 174 | ![](http://matplotlib.org/_images/tight_layout_guide-11.png) 175 | 176 | 我们可以尝试匹配两个网格的顶部和底部。 177 | 178 | ```py 179 | top = min(gs1.top, gs2.top) 180 | bottom = max(gs1.bottom, gs2.bottom) 181 | 182 | gs1.update(top=top, bottom=bottom) 183 | gs2.update(top=top, bottom=bottom) 184 | ``` 185 | 186 | 虽然这应该足够好了,调整顶部和底部可能也需要调整`hspace`。 为了更新`hspace`和`vspace`,我们再次使用更新后的`rect`参数调用`tight_layout()`。 注意,`rect`参数指定的区域包括刻度标签。因此,我们将底部(正常情况下为 0)增加每个`gridspec`的底部之差。 顶部也一样。 187 | 188 | 189 | ```py 190 | top = min(gs1.top, gs2.top) 191 | bottom = max(gs1.bottom, gs2.bottom) 192 | 193 | gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom), 194 | 0.5, 1 - (gs1.top-top)]) 195 | gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom), 196 | None, 1 - (gs2.top-top)], 197 | h_pad=0.5) 198 | ``` 199 | 200 | ![](http://matplotlib.org/_images/tight_layout_guide-12.png) 201 | 202 | ## 和`AxesGrid1`一起使用 203 | 204 | 虽然受限但也支持`axes_grid1`工具包 205 | 206 | ```py 207 | plt.close('all') 208 | fig = plt.figure() 209 | 210 | from mpl_toolkits.axes_grid1 import Grid 211 | grid = Grid(fig, rect=111, nrows_ncols=(2,2), 212 | axes_pad=0.25, label_mode='L', 213 | ) 214 | 215 | for ax in grid: 216 | example_plot(ax) 217 | ax.title.set_visible(False) 218 | 219 | plt.tight_layout() 220 | ``` 221 | 222 | ![](http://matplotlib.org/_images/tight_layout_guide-13.png) 223 | 224 | ## 颜色条 225 | 226 | 如果你使用`colorbar`命令创建了颜色条,创建的颜色条是`Axes`而不是`Subplot`的实例,所以`tight_layout`没有效果。在 Matplotlib v1.1 中,你可以使用`gridspec`将颜色条创建为子图。 227 | 228 | ```py 229 | plt.close('all') 230 | arr = np.arange(100).reshape((10,10)) 231 | fig = plt.figure(figsize=(4, 4)) 232 | im = plt.imshow(arr, interpolation="none") 233 | 234 | plt.colorbar(im, use_gridspec=True) 235 | 236 | plt.tight_layout() 237 | ``` 238 | 239 | ![])http://matplotlib.org/_images/tight_layout_guide-14.png 240 | 241 | 另一个选项是使用`AxesGrid1`工具包,显式为颜色条创建一个轴域: 242 | 243 | ```py 244 | plt.close('all') 245 | arr = np.arange(100).reshape((10,10)) 246 | fig = plt.figure(figsize=(4, 4)) 247 | im = plt.imshow(arr, interpolation="none") 248 | 249 | from mpl_toolkits.axes_grid1 import make_axes_locatable 250 | divider = make_axes_locatable(plt.gca()) 251 | cax = divider.append_axes("right", "5%", pad="3%") 252 | plt.colorbar(im, cax=cax) 253 | 254 | plt.tight_layout() 255 | ``` 256 | 257 | ![](http://matplotlib.org/_images/tight_layout_guide-15.png) 258 | -------------------------------------------------------------------------------- /3.5.md: -------------------------------------------------------------------------------- 1 | # 艺术家教程 2 | 3 | > 原文:[Artist tutorial](http://matplotlib.org/users/artists.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | matplotlib API 有三个层级。 `matplotlib.backend_bases.FigureCanvas`是绘制图形的区域,`matplotlib.backend_bases.Renderer`是知道如何在`ChartCanvas`上绘制的对象,而`matplotlib.artist.Artist`是知道如何使用渲染器在画布上画图的对象。 `FigureCanvas`和`Renderer`处理与用户界面工具包(如 wxPython)或 PostScript® 等绘图语言交互的所有细节,`Artist`处理所有高级结构,如表示和布局图形,文本和线条。用户通常要花费95%的时间来处理艺术家。 10 | 11 | 有两种类型的艺术家:基本类型和容器类型。基本类型表示我们想要绘制到画布上的标准图形对象:`Line2D`,`Rectangle`,`Text`,`AxesImage`等,容器是放置它们的位置(`Axis`,`Axes`和`Figure`)。标准用法是创建一个`Figure`实例,使用`Figure`创建一个或多个`Axes`或`Subplot`实例,并使用`Axes`实例的辅助方法来创建基本类型。在下面的示例中,我们使用`matplotlib.pyplot.figure()`创建一个`Figure`实例,这是一个便捷的方法,用于实例化`Figure`实例并将它们与你的用户界面或绘图工具包`FigureCanvas`连接。正如我们将在下面讨论的,这不是必须的 - 你可以直接使用 PostScript,PDF,Gtk+ 或 wxPython `FigureCanvas`实例,直接实例化你的图形并连接它们 - 但是因为我们在这里关注艺术家 API,我们让`pyplot`为我们处理一些细节: 12 | 13 | ```py 14 | import matplotlib.pyplot as plt 15 | fig = plt.figure() 16 | ax = fig.add_subplot(2,1,1) # two rows, one column, first plot 17 | ``` 18 | 19 | `Axes`可能是 matplotlib API 中最重要的类,你将在大多数时间使用它。 这是因为`Axes`是大多数对象所进入的绘图区域,`Axes`有许多特殊的辅助方法(`plot()`,`text()`,`hist()`,`imshow()`)来创建最常见的图形基本类型 `Line2D`,`Text`,`Rectangle`,`Image`)。 这些辅助方法将获取你的数据(例如 numpy 数组和字符串),并根据需要创建基本`Artist`实例(例如,`Line2D`),将它们添加到相关容器中,并在请求时绘制它们。 大多数人可能熟悉子图,这只是`Axes`的一个特例,它存在于`Subplot`实例的列网格的固定行上。 如果要在任意位置创建`Axes`,只需使用`add_axes()`方法,该方法接受`[left, bottom, width, height]`值的列表,以 0~1 的图形相对坐标为单位: 20 | 21 | ```PY 22 | fig2 = plt.figure() 23 | ax2 = fig2.add_axes([0.15, 0.1, 0.7, 0.3]) 24 | ``` 25 | 26 | 以我们的例子继续: 27 | 28 | ```py 29 | import numpy as np 30 | t = np.arange(0.0, 1.0, 0.01) 31 | s = np.sin(2*np.pi*t) 32 | line, = ax.plot(t, s, color='blue', lw=2) 33 | ``` 34 | 35 | 在这个例子中,`ax`是上面的`fig.add_subplot`调用创建的`Axes`实例(记住`Subplot`只是`Axes`的一个子类),当你调用`ax.plot`时,它创建一个`Line2D`实例并将其添加到`Axes.lines`列表中。 在下面的 ipython 交互式会话中,你可以看到`Axes.lines`列表的长度为 1,并且包含由`line, = ax.plot... `调用返回的相同线条: 36 | 37 | ```py 38 | In [101]: ax.lines[0] 39 | Out[101]: 40 | 41 | In [102]: line 42 | Out[102]: 43 | ``` 44 | 45 | 如果你对`ax.plot`进行连续调用(并且保持状态为『on』,这是默认值),则将在列表中添加其他线条。 你可以稍后通过调用列表方法删除线条;任何一个方法都可以: 46 | 47 | ```py 48 | del ax.lines[0] 49 | ax.lines.remove(line) # one or the other, not both! 50 | ``` 51 | 52 | 轴域也拥有辅助方法,用于设置和装饰 x 和 y 轴的刻度、刻度标签和轴标签: 53 | 54 | ```py 55 | xtext = ax.set_xlabel('my xdata') # returns a Text instance 56 | ytext = ax.set_ylabel('my ydata') 57 | ``` 58 | 59 | 当你调用`ax.set_xlabel`时,它将信息传递给`XAxis`的`Text`实例,每个`Axes `实例都包含`XAxis`和`YAxis`,它们处理刻度、刻度标签和轴标签的布局和绘制。 60 | 61 | 尝试创建下面的图形: 62 | 63 | ![](http://matplotlib.org/_images/fig_axes_labels_simple.png) 64 | 65 | ## 自定义你的对象 66 | 67 | 图中的每个元素都由一个 matplotlib 艺术家表示,每个元素都有一个扩展属性列表用于配置它的外观。 图形本身包含一个`Rectangle`,正好是图形的大小,你可以使用它来设置图形的背景颜色和透明度。 同样,每个`Axes`边框(在通常的 matplotlib 绘图中是标准的白底黑边)拥有一个`Rectangle`实例,用于确定轴域的颜色,透明度和其他属性,这些实例存储为成员变量`Figure.patch`和`Axes.patch`(『Patch』是一个继承自 MATLAB 的名称,它是图形上的一个颜色的 2D『补丁』,例如矩形,圆和多边形)。每个 matplotlib 艺术家都有以下属性。 68 | 69 | | 属性 | 描述 | 70 | | --- | --- | 71 | | alpha | 透明度 - 0 ~ 1 的标量 | 72 | | animated | 用于帮助动画绘制的布尔值 | 73 | | axes | 艺术家所在的轴域,可能为空 | 74 | | clip_box | 用于剪切艺术家的边框 | 75 | | clip_on | 剪切是否开启 | 76 | | clip_path | 艺术家被剪切的路径 | 77 | | contains | 一个拾取函数,用于判断艺术家是否位于拾取点 | 78 | | figure | 艺术家所在的图形实例,可能为空 | 79 | | label | 文本标签(用于自动标记) | 80 | | picker | 控制对象拾取的 Python 对象 | 81 | | transform | 变换 | 82 | | visible | 布尔值,表示艺术家是否应该绘制 | 83 | | zorder | 确定绘制顺序的数值 | 84 | | rasterized | 布尔值,是否将向量转换为光栅图形(出于压缩或 eps 透明度) | 85 | 86 | 每个属性都使用一个老式的`setter`或`getter`(是的,我们知道这会刺激 Python 爱好者,我们计划支持通过属性或 traits 直接访问,但它还没有完成)。 例如,要将当前`alpha`值变为一半: 87 | 88 | ```py 89 | a = o.get_alpha() 90 | o.set_alpha(0.5*a) 91 | ``` 92 | 93 | 如果你打算可以一次性设置一些属性,你也可以以关键字参数使用`set`方法,例如: 94 | 95 | ```py 96 | o.set(alpha=0.5, zorder=2) 97 | ``` 98 | 99 | 如果你在 Python 交互式 Shell 中工作,检查`Artist`属性的一种方便的方法是使用`matplotlib.artist.getp()`函数(在 pylab 中只需要`getp()`),它列出了属性及其值。 这适用于从`Artist`派生的类,例如`Figure`和`Rectangle`。 这里是上面提到的`Figure`的矩形属性: 100 | 101 | ```py 102 | In [149]: matplotlib.artist.getp(fig.patch) 103 | alpha = 1.0 104 | animated = False 105 | antialiased or aa = True 106 | axes = None 107 | clip_box = None 108 | clip_on = False 109 | clip_path = None 110 | contains = None 111 | edgecolor or ec = w 112 | facecolor or fc = 0.75 113 | figure = Figure(8.125x6.125) 114 | fill = 1 115 | hatch = None 116 | height = 1 117 | label = 118 | linewidth or lw = 1.0 119 | picker = None 120 | transform = 121 | verts = ((0, 0), (0, 1), (1, 1), (1, 0)) 122 | visible = True 123 | width = 1 124 | window_extent = 125 | x = 0 126 | y = 0 127 | zorder = 1 128 | ``` 129 | 130 | 所有类的文档字符串也包含`Artist`属性,因此你可以查阅交互式『帮助』或 [`Artist`模块](http://matplotlib.org/api/artist_api.html#artist-api),来获取给定对象的属性列表。 131 | 132 | 133 | ## 对象容器 134 | 135 | 现在我们知道如何检查和设置我们想要配置的给定对象的属性,现在我们需要如何获取该对象。 前面提到了两种对象:基本类型和容器类型。 基本类型通常是你想要配置的东西(`Text`实例的字体,`Line2D`的宽度),虽然容器也有一些属性 - 例如 `Axes`是一个容器艺术家,包含你的绘图中的许多基本类型,但它也有属性,比如`xscale`来控制`xaxis`是『线性』还是『对数』。 在本节中,我们将回顾各种容器对象存储你想要访问的艺术家的位置。 136 | 137 | ## 图形容器 138 | 139 | 顶层容器艺术家是`matplotlib.figure.Figure`,它包含图形中的所有内容。 图形的背景是一个`Rectangle`,存储在`Figure.patch`中。 当你向图形中添加子图(`add_subplot()`)和轴域(`add_axes()`)时,这些会附加到`Figure.axes`。 它们也由创建它们的方法返回: 140 | 141 | ```py 142 | In [156]: fig = plt.figure() 143 | 144 | In [157]: ax1 = fig.add_subplot(211) 145 | 146 | In [158]: ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3]) 147 | 148 | In [159]: ax1 149 | Out[159]: 150 | 151 | In [160]: print fig.axes 152 | [, ] 153 | ``` 154 | 155 | 因为图形维护了『当前轴域』(见`figure.gca`和图`figure.sca`)的概念以支持 pylab/pyplot 状态机,所以不应直接从轴域列表中插入或删除轴域,而应使用`add_subplot()`和`add_axes()`方法进行插入,并使用`delaxes()`方法进行删除。 然而,你可以自由地遍历轴域列表或索引,来访问要自定义的`Axes`实例。 下面是一个打开所有轴域网格的示例: 156 | 157 | ```py 158 | for ax in fig.axes: 159 | ax.grid(True) 160 | ``` 161 | 162 | 图形还拥有自己的文本,线条,补丁和图像,你可以使用它们直接添加基本类型。 图形的默认坐标系统简单地以像素(这通常不是你想要的)为单位,但你可以通过设置你添加到图中的艺术家的`transform`属性来控制它。 163 | 164 | 更有用的是『图形坐标系』,其中`(0,0)`是图的左下角,`(1,1)`是图的右上角,你可以通过将`Artist`的变换设置为`fig.transFigure`来获得: 165 | 166 | ```py 167 | In [191]: fig = plt.figure() 168 | 169 | In [192]: l1 = matplotlib.lines.Line2D([0, 1], [0, 1], 170 | transform=fig.transFigure, figure=fig) 171 | 172 | In [193]: l2 = matplotlib.lines.Line2D([0, 1], [1, 0], 173 | transform=fig.transFigure, figure=fig) 174 | 175 | In [194]: fig.lines.extend([l1, l2]) 176 | 177 | In [195]: fig.canvas.draw() 178 | ``` 179 | 180 | ![](http://matplotlib.org/_images/fig_x.png) 181 | 182 | 这里是图形可以包含的艺术家总结: 183 | 184 | 185 | | 图形属性 | 描述 | 186 | | --- | --- | 187 | | `axes` | `Axes`实例的列表(包括`Subplot`) | 188 | | `patch` | `Rectangle`背景 | 189 | | `images` | `FigureImages`补丁的列表 - 用于原始像素显示 | 190 | | `legends` | 图形`Legend`实例的列表(不同于`Axes.legends`) | 191 | | `lines` | 图形`Line2D`实例的列表(很少使用,见`Axes.lines`) | 192 | | `patches` | 图形补丁列表(很少使用,见`Axes.patches`) | 193 | | `texts` | 图形`Text`实例的列表 | 194 | 195 | ## 轴域容器 196 | 197 | `matplotlib.axes.Axes`是 matplotlib 宇宙的中心 - 它包含绝大多数在一个图形中使用的艺术家,并带有许多辅助方法来创建和添加这些艺术家本身,以及访问和自定义所包含的艺术家的辅助方法。 就像`Figure`那样,它包含一个`Patch patch`,它是一个用于笛卡尔坐标的`Rectangle`和一个用于极坐标的`Cirecle`; 这个补丁决定了绘图区域的形状,背景和边框: 198 | 199 | ```py 200 | ax = fig.add_subplot(111) 201 | rect = ax.patch # a Rectangle instance 202 | rect.set_facecolor('green') 203 | ``` 204 | 205 | 当调用绘图方法(例如通常是`plot()`)并传递数组或值列表时,该方法将创建一个`matplotlib.lines.Line2D()`实例,将所有`Line2D`属性作为关键字参数传递, 将该线条添加到`Axes.lines`容器,并将其返回给你: 206 | 207 | ```py 208 | In [213]: x, y = np.random.rand(2, 100) 209 | 210 | In [214]: line, = ax.plot(x, y, '-', color='blue', linewidth=2) 211 | ``` 212 | 213 | `plot`返回一个线条列表,因为你可以传入多个`x,y`偶对来绘制,我们将长度为一的列表的第一个元素解构到`line`变量中。 该线条已添加到`Axes.lines`列表中: 214 | 215 | ```py 216 | In [229]: print ax.lines 217 | [] 218 | ``` 219 | 220 | 与之类似,创建补丁的方法(如`bar()`)会创建一个矩形列表,将补丁添加到`Axes.patches`列表中: 221 | 222 | ```py 223 | In [233]: n, bins, rectangles = ax.hist(np.random.randn(1000), 50, facecolor='yellow') 224 | 225 | In [234]: rectangles 226 | Out[234]: 227 | 228 | In [235]: print len(ax.patches) 229 | ``` 230 | 231 | 你不应该直接将对象添加到`Axes.lines`或`Axes.patches`列表,除非你确切知道你在做什么,因为`Axes`需要在它创建和添加对象做一些事情。 它设置`Artist`的`figure`和`axes`属性,以及默认`Axes`变换(除非设置了变换)。 它还检查`Artist`中包含的数据,来更新控制自动缩放的数据结构,以便可以调整视图限制来包含绘制的数据。 但是,你可以自己创建对象,并使用辅助方法(如`add_line()`和`add_patch()`)将它们直接添加到`Axes`。 这里是一个注释的交互式会话,说明正在发生什么: 232 | 233 | ```py 234 | In [261]: fig = plt.figure() 235 | 236 | In [262]: ax = fig.add_subplot(111) 237 | 238 | # create a rectangle instance 239 | In [263]: rect = matplotlib.patches.Rectangle( (1,1), width=5, height=12) 240 | 241 | # by default the axes instance is None 242 | In [264]: print rect.get_axes() 243 | None 244 | 245 | # and the transformation instance is set to the "identity transform" 246 | In [265]: print rect.get_transform() 247 | 248 | 249 | # now we add the Rectangle to the Axes 250 | In [266]: ax.add_patch(rect) 251 | 252 | # and notice that the ax.add_patch method has set the axes 253 | # instance 254 | In [267]: print rect.get_axes() 255 | Axes(0.125,0.1;0.775x0.8) 256 | 257 | # and the transformation has been set too 258 | In [268]: print rect.get_transform() 259 | 260 | 261 | # the default axes transformation is ax.transData 262 | In [269]: print ax.transData 263 | 264 | 265 | # notice that the xlimits of the Axes have not been changed 266 | In [270]: print ax.get_xlim() 267 | (0.0, 1.0) 268 | 269 | # but the data limits have been updated to encompass the rectangle 270 | In [271]: print ax.dataLim.bounds 271 | (1.0, 1.0, 5.0, 12.0) 272 | 273 | # we can manually invoke the auto-scaling machinery 274 | In [272]: ax.autoscale_view() 275 | 276 | # and now the xlim are updated to encompass the rectangle 277 | In [273]: print ax.get_xlim() 278 | (1.0, 6.0) 279 | 280 | # we have to manually force a figure draw 281 | In [274]: ax.figure.canvas.draw() 282 | ``` 283 | 284 | 有非常多的`Axes`辅助方法用于创建基本艺术家并将它们添加到他们各自的容器中。 下表总结了他们的一部分,他们创造的`Artist`的种类,以及他们在哪里存储它们。 285 | 286 | 287 | | 辅助方法 | 艺术家 | 容器 | 288 | | --- | --- | --- | 289 | | `ax.annotate` - 文本标注 | `Annotate` | `ax.texts` | 290 | | `ax.bar` - 条形图 | `Rectangle` | `ax.patches` | 291 | | `ax.errorbar` - 误差条形图 | `Line2D` 和 `Rectangle` | `ax.lines` 和 `ax.patches` | 292 | | `ax.fill` - 共享区域 | `Polygon` | `ax.patches` | 293 | | `ax.hist` - 直方图 | `Rectangle` | `ax.patches` | 294 | | `ax.imshow` - 图像数据 | `AxesImage` | `ax.images` | 295 | | `ax.legend` - 轴域图例 | `Legend` | `ax.legends` | 296 | | `ax.plot` - xy 绘图 | `Line2D` | `ax.lines` | 297 | | `ax.scatter` - 散点图 | `PolygonCollection` | `ax.collections` | 298 | | `ax.text` - 文本 | `Text` | `ax.texts` | 299 | 300 | 除了所有这些艺术家,`Axes`包含两个重要的艺术家容器:`XAxis`和`YAxis`,它们处理刻度和标签的绘制。 它们被存储为实例变量`xaxis`和`yaxis`。 `XAxis`和`YAxis`容器将在下面详细介绍,但请注意,`Axes`包含许多辅助方法,它们会将调用转发给`Axis`实例,因此你通常不需要直接使用它们,除非你愿意。 例如,你可以使用`Axes`辅助程序方法设置`XAxis`刻度标签的字体大小: 301 | 302 | ```py 303 | for label in ax.get_xticklabels(): 304 | label.set_color('orange') 305 | ``` 306 | 307 | 下面是轴域所包含的艺术家的总结 308 | 309 | | 轴域属性 | 描述 | 310 | | --- | --- | 311 | | `artists` | `Artist`实例的列表 | 312 | | `patch` | 用于轴域背景的`Rectangle`实例 | 313 | | `collections` | `Collection`实例的列表 | 314 | | `images` | `AxesImage`的列表 | 315 | | `legends` | `Legend`实例的列表 | 316 | | `lines` | `Line2D`实例的列表 | 317 | | `patches` | `Patch`实例的列表 | 318 | | `texts` | `Text`实例的列表 | 319 | | `xaxis` | `matplotlib.axis.XAxis`实例 | 320 | | `yaxis` | `matplotlib.axis.YAxis`实例 | 321 | 322 | ## 轴容器 323 | 324 | `matplotlib.axis.Axis`实例处理刻度线,网格线,刻度标签和轴标签的绘制。你可以分别为y轴配置左和右刻度,为x轴分别配置上和下刻度。 `Axis`还存储在自动缩放,平移和缩放中使用的数据和视图间隔,以及`Locator`和`Formatter`实例,它们控制刻度位置以及它们表示为字符串的方式。 325 | 326 | 每个`Axis`对象都包含一个`label`属性(这是 pylab 在调用`xlabel()`和`ylabel()`时修改的东西)以及主和次刻度的列表。刻度是`XTick`和`YTick`实例,它包含渲染刻度和刻度标签的实际线条和文本基本类型。因为刻度是按需动态创建的(例如,当平移和缩放时),你应该通过访问器方法`get_major_ticks()`和`get_minor_ticks()`访问主和次刻度的列表。虽然刻度包含所有下面要提及的基本类型,`Axis`方法包含访问器方法来返回刻度线,刻度标签,刻度位置等: 327 | 328 | ```py 329 | In [285]: axis = ax.xaxis 330 | 331 | In [286]: axis.get_ticklocs() 332 | Out[286]: array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) 333 | 334 | In [287]: axis.get_ticklabels() 335 | Out[287]: 336 | 337 | # note there are twice as many ticklines as labels because by 338 | # default there are tick lines at the top and bottom but only tick 339 | # labels below the xaxis; this can be customized 340 | In [288]: axis.get_ticklines() 341 | Out[288]: 342 | 343 | # by default you get the major ticks back 344 | In [291]: axis.get_ticklines() 345 | Out[291]: 346 | 347 | # but you can also ask for the minor ticks 348 | In [292]: axis.get_ticklines(minor=True) 349 | Out[292]: 350 | ``` 351 | 352 | 下面是`Axis`的一些有用的访问器方法的总结(它们拥有相应的`setter`,如`set_major_formatter`)。 353 | 354 | 355 | | 访问器方法 | 描述 | 356 | | --- | --- | 357 | | get_scale | 轴的比例,例如`'log'`或`'linear'` | 358 | | get_view_interval | 轴视图范围的内部实例 | 359 | | get_data_interval | 轴数据范围的内部实例 | 360 | | get_gridlines | 轴的网格线列表 | 361 | | get_label | 轴标签 - `Text`实例 | 362 | | get_ticklabels | `Text`实例的列表 - 关键字`minor=True|False` | 363 | | get_ticklines | `Line2D`实例的列表 - 关键字`minor=True|False` | 364 | | get_ticklocs | `Tick`位置的列表 - 关键字`minor=True|False` | 365 | | get_major_locator | 用于主刻度的`matplotlib.ticker.Locator`实例 | 366 | | get_major_formatter | 用于主刻度的`matplotlib.ticker.Formatter`实例 | 367 | | get_minor_locator | 用于次刻度的`matplotlib.ticker.Locator`实例 | 368 | | get_minor_formatter | 用于次刻度的`matplotlib.ticker.Formatter`实例 | 369 | | get_major_ticks | 用于主刻度的`Tick`实例列表 | 370 | | get_minor_ticks | 用于次刻度的`Tick`实例列表 | 371 | | grid | 为主或次刻度打开或关闭网格 | 372 | 373 | 这里是个例子,出于美观不太推荐,它自定义了轴域和刻度属性。 374 | 375 | ```py 376 | import numpy as np 377 | import matplotlib.pyplot as plt 378 | 379 | # plt.figure creates a matplotlib.figure.Figure instance 380 | fig = plt.figure() 381 | rect = fig.patch # a rectangle instance 382 | rect.set_facecolor('lightgoldenrodyellow') 383 | 384 | ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) 385 | rect = ax1.patch 386 | rect.set_facecolor('lightslategray') 387 | 388 | 389 | for label in ax1.xaxis.get_ticklabels(): 390 | # label is a Text instance 391 | label.set_color('red') 392 | label.set_rotation(45) 393 | label.set_fontsize(16) 394 | 395 | for line in ax1.yaxis.get_ticklines(): 396 | # line is a Line2D instance 397 | line.set_color('green') 398 | line.set_markersize(25) 399 | line.set_markeredgewidth(3) 400 | 401 | plt.show() 402 | ``` 403 | 404 | ![](http://matplotlib.org/_images/fig_axes_customize_simple.png) 405 | 406 | ## 刻度容器 407 | 408 | `matplotlib.axis.Tick`是我们从`Figure`到`Axes`再到`Axis`再到`Tick`的最终的容器对象。`Tick`包含刻度和网格线的实例,以及上侧和下侧刻度的标签实例。 每个都可以直接作为`Tick`的属性访问。此外,也有用于确定上标签和刻度是否对应`x`轴,以及右标签和刻度是否对应`y`轴的布尔变量。 409 | 410 | 411 | | 刻度属性 | 描述 | 412 | | --- | --- | 413 | | `tick1line` | `Line2D`实例 | 414 | | `tick2line` | `Line2D`实例 | 415 | | `gridline` | `Line2D`实例 | 416 | | `label1` | `Text`实例 | 417 | | `label2` | `Text`实例 | 418 | | `gridOn` | 确定是否绘制刻度线的布尔值 | 419 | | `tick1On` | 确定是否绘制主刻度线的布尔值 | 420 | | `tick2On` | 确定是否绘制次刻度线的布尔值 | 421 | | `label1On` | 确定是否绘制主刻度标签的布尔值 | 422 | | `label2On` | 确定是否绘制次刻度标签的布尔值 | 423 | 424 | 这里是个例子,使用美元符号设置右侧刻度,并在`y`轴右侧将它们设成绿色。 425 | 426 | ```py 427 | import numpy as np 428 | import matplotlib.pyplot as plt 429 | import matplotlib.ticker as ticker 430 | 431 | # Fixing random state for reproducibility 432 | np.random.seed(19680801) 433 | 434 | fig = plt.figure() 435 | ax = fig.add_subplot(111) 436 | ax.plot(100*np.random.rand(20)) 437 | 438 | formatter = ticker.FormatStrFormatter('$%1.2f') 439 | ax.yaxis.set_major_formatter(formatter) 440 | 441 | for tick in ax.yaxis.get_major_ticks(): 442 | tick.label1On = False 443 | tick.label2On = True 444 | tick.label2.set_color('green') 445 | 446 | plt.show() 447 | ``` 448 | 449 | ![](http://matplotlib.org/_images/dollar_ticks.png) 450 | -------------------------------------------------------------------------------- /3.6.md: -------------------------------------------------------------------------------- 1 | # 图例指南 2 | 3 | > 原文:[Legend guide](http://matplotlib.org/users/legend_guide.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 此图例指南是`legend()`中可用文档的扩展 - 请在继续阅读本指南之前确保你熟悉该文档(见篇尾)的内容。 10 | 11 | 本指南使用一些常见术语,为了清楚起见,这些术语在此处进行说明: 12 | 13 | 图例条目 14 | 15 | 图例由一个或多个图例条目组成。 一个条目由一个键和一个标签组成。 16 | 17 | 图例键 18 | 19 | 每个图例标签左侧的彩色/图案标记。 20 | 21 | 图例标签 22 | 23 | 描述由键表示的句柄的文本。 24 | 25 | 图例句柄 26 | 27 | 用于在图例中生成适当条目的原始对象。 28 | 29 | ## 控制图例条目 30 | 31 | 不带参数调用`legend()`会自动获取图例句柄及其相关标签。 此函数等同于: 32 | 33 | ```py 34 | handles, labels = ax.get_legend_handles_labels() 35 | ax.legend(handles, labels) 36 | ``` 37 | 38 | `get_legend_handles_labels()`函数返回轴域上存在的句柄/艺术家的列表,这些句柄/艺术家可以用于为结果图例生成条目 - 但值得注意的是,并非所有艺术家都可以添加到图例中, 这种情况下会创建『代理』(请参阅[特地为添加到图例创建艺术家(也称为代理艺术家)](http://matplotlib.org/users/legend_guide.html#proxy-legend-handles),来了解更多详细信息)。 39 | 40 | 为了完全控制要添加到图例的内容,通常将适当的句柄直接传递给`legend()`: 41 | 42 | ```py 43 | line_up, = plt.plot([1,2,3], label='Line 2') 44 | line_down, = plt.plot([3,2,1], label='Line 1') 45 | plt.legend(handles=[line_up, line_down]) 46 | ``` 47 | 48 | 在某些情况下,不可能设置句柄的标签,因此可以将标签列表传递给`legend()`: 49 | 50 | ```py 51 | line_up, = plt.plot([1,2,3], label='Line 2') 52 | line_down, = plt.plot([3,2,1], label='Line 1') 53 | plt.legend([line_up, line_down], ['Line Up', 'Line Down']) 54 | ``` 55 | 56 | ## 特地为添加到图例创建艺术家(也称为代理艺术家) 57 | 58 | 并非所有的句柄都可以自动转换为图例条目,因此通常需要创建一个可转换的艺术家。 图例句柄不必存在于被用到的图像或轴域上。 59 | 60 | 假设我们想创建一个图例,其中有一些数据表示为红色: 61 | 62 | ```py 63 | import matplotlib.patches as mpatches 64 | import matplotlib.pyplot as plt 65 | 66 | red_patch = mpatches.Patch(color='red', label='The red data') 67 | plt.legend(handles=[red_patch]) 68 | 69 | plt.show() 70 | ``` 71 | 72 | ![](http://matplotlib.org/_images/legend_guide-1.png) 73 | 74 | 除了创建一个色块之外,有许多受支持的图例句柄,我们可以创建一个带有标记的线条: 75 | 76 | ```py 77 | import matplotlib.lines as mlines 78 | import matplotlib.pyplot as plt 79 | 80 | blue_line = mlines.Line2D([], [], color='blue', marker='*', 81 | markersize=15, label='Blue stars') 82 | plt.legend(handles=[blue_line]) 83 | 84 | plt.show() 85 | ``` 86 | 87 | ## 图例位置 88 | 89 | 图例的位置可以通过关键字参数`loc`指定。 详细信息请参阅`legend()`的文档。 90 | 91 | `bbox_to_anchor`关键字可让用户手动控制图例布局。 例如,如果你希望轴域图例位于图像的右上角而不是轴域的边角,则只需指定角的位置以及该位置的坐标系: 92 | 93 | ```py 94 | plt.legend(bbox_to_anchor=(1, 1), 95 | bbox_transform=plt.gcf().transFigure) 96 | ``` 97 | 98 | 自定义图例位置的更多示例: 99 | 100 | ```py 101 | import matplotlib.pyplot as plt 102 | 103 | 104 | plt.subplot(211) 105 | plt.plot([1,2,3], label="test1") 106 | plt.plot([3,2,1], label="test2") 107 | # 将图例放到这个子图上方, 108 | # 扩展自身来完全利用提供的边界框。 109 | plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, 110 | ncol=2, mode="expand", borderaxespad=0.) 111 | 112 | plt.subplot(223) 113 | plt.plot([1,2,3], label="test1") 114 | plt.plot([3,2,1], label="test2") 115 | # 将图例放到这个小型子图的右侧 116 | plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 117 | 118 | plt.show() 119 | ``` 120 | 121 | ![](http://matplotlib.org/_images/simple_legend01.png) 122 | 123 | ## 相同轴域内的多个图例 124 | 125 | 有时,在多个图例之间分割图例条目会更加清晰。 虽然直觉上的做法可能是多次调用`legend()`函数,但你会发现轴域上只存在一个图例。 这样做是为了可以重复调用`legend()`,将图例更新为轴域上的最新句柄,因此要保留旧的图例实例,我们必须将它们手动添加到轴域中: 126 | 127 | ```py 128 | import matplotlib.pyplot as plt 129 | 130 | line1, = plt.plot([1,2,3], label="Line 1", linestyle='--') 131 | line2, = plt.plot([3,2,1], label="Line 2", linewidth=4) 132 | 133 | # 为第一个线条创建图例 134 | first_legend = plt.legend(handles=[line1], loc=1) 135 | 136 | # 手动将图例添加到当前轴域 137 | ax = plt.gca().add_artist(first_legend) 138 | 139 | # 为第二个线条创建另一个图例 140 | plt.legend(handles=[line2], loc=4) 141 | 142 | plt.show() 143 | ``` 144 | 145 | ![](http://matplotlib.org/_images/simple_legend02.png) 146 | 147 | ## 图例处理器 148 | 149 | 为了创建图例条目,将句柄作为参数提供给适当的`HandlerBase`子类。 处理器子类的选择由以下规则确定: 150 | 151 | + 使用`handler_map`关键字中的值更新`get_legend_handler_map()`。 152 | + 检查句柄是否在新创建的`handler_map`中。 153 | + 检查句柄的类型是否在新创建的`handler_map`中。 154 | + 检查句柄的`mro`中的任何类型是否在新创建的`handler_map`中。 155 | 156 | 处于完整性,这个逻辑大多在`get_legend_handler()`中实现。 157 | 158 | 所有这些灵活性意味着我们可以使用一些必要的钩子,为我们自己的图例键类型实现自定义处理器。 159 | 160 | 使用自定义处理器的最简单的例子是,实例化一个现有的`HandlerBase`子类。 为了简单起见,让我们选择`matplotlib.legend_handler.HandlerLine2D`,它接受`numpoints`参数(出于便利,注意`numpoints`是`legend()`函数上的一个关键字)。 然后我们可以将实例的字典作为关键字`handler_map`传给`legend`。 161 | 162 | ```py 163 | import matplotlib.pyplot as plt 164 | from matplotlib.legend_handler import HandlerLine2D 165 | 166 | line1, = plt.plot([3,2,1], marker='o', label='Line 1') 167 | line2, = plt.plot([1,2,3], marker='o', label='Line 2') 168 | 169 | plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)}) 170 | ``` 171 | 172 | ![](http://matplotlib.org/_images/legend_guide-3.png) 173 | 174 | 如你所见,`Line 1`现在有 4 个标记点,`Line 2`有两个(默认值)。 尝试上面的代码,只需将字典的键从`line1`更改为type(line)`。 注意现在两个`Line2D`实例都拥有了 4 个标记。 175 | 176 | 除了用于复杂的绘图类型的处理器,如误差条,茎叶图和直方图,默认的`handler_map`有一个特殊的元组处理器(`HandlerTuple`),它简单地在顶部一一绘制给定元组中每个项目的句柄。 以下示例演示如何将两个图例的键相互叠加: 177 | 178 | ```py 179 | import matplotlib.pyplot as plt 180 | from numpy.random import randn 181 | 182 | z = randn(10) 183 | 184 | red_dot, = plt.plot(z, "ro", markersize=15) 185 | # 将白色十字放置在一些数据上 186 | white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15) 187 | 188 | plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"]) 189 | ``` 190 | 191 | ![](http://matplotlib.org/_images/legend_guide-4.png) 192 | 193 | ### 实现自定义图例处理器 194 | 195 | 196 | 可以实现自定义处理器,将任何句柄转换为图例的键(句柄不必要是`matplotlib`artist)。 处理器必须实现`legend_artist`方法,该方法为要使用的图例返回单个艺术家。 有关`legend_artist`的详细信息,请参阅[`legend_artist()`](http://matplotlib.org/api/legend_api.html#matplotlib.legend_handler.HandlerBase.legend_artist)。 197 | 198 | ```py 199 | import matplotlib.pyplot as plt 200 | import matplotlib.patches as mpatches 201 | 202 | class AnyObject(object): 203 | pass 204 | 205 | class AnyObjectHandler(object): 206 | def legend_artist(self, legend, orig_handle, fontsize, handlebox): 207 | x0, y0 = handlebox.xdescent, handlebox.ydescent 208 | width, height = handlebox.width, handlebox.height 209 | patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red', 210 | edgecolor='black', hatch='xx', lw=3, 211 | transform=handlebox.get_transform()) 212 | handlebox.add_artist(patch) 213 | return patch 214 | 215 | plt.legend([AnyObject()], ['My first handler'], 216 | handler_map={AnyObject: AnyObjectHandler()}) 217 | ``` 218 | 219 | ![](http://matplotlib.org/_images/legend_guide-5.png) 220 | 221 | 或者,如果我们想要接受全局的`AnyObject`实例,而不想一直手动设置`handler_map`关键字,我们可以注册新的处理器: 222 | 223 | ```py 224 | from matplotlib.legend import Legend 225 | Legend.update_default_handler_map({AnyObject: AnyObjectHandler()}) 226 | ``` 227 | 228 | 虽然这里的功能十分清楚,请记住,有很多已实现的处理器,你想实现的目标可能易于使用现有的类实现。 例如,要生成椭圆的图例键,而不是矩形键: 229 | 230 | ```py 231 | from matplotlib.legend_handler import HandlerPatch 232 | import matplotlib.pyplot as plt 233 | import matplotlib.patches as mpatches 234 | 235 | 236 | class HandlerEllipse(HandlerPatch): 237 | def create_artists(self, legend, orig_handle, 238 | xdescent, ydescent, width, height, fontsize, trans): 239 | center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent 240 | p = mpatches.Ellipse(xy=center, width=width + xdescent, 241 | height=height + ydescent) 242 | self.update_prop(p, orig_handle, legend) 243 | p.set_transform(trans) 244 | return [p] 245 | 246 | 247 | c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green", 248 | edgecolor="red", linewidth=3) 249 | plt.gca().add_patch(c) 250 | 251 | plt.legend([c], ["An ellipse, not a rectangle"], 252 | handler_map={mpatches.Circle: HandlerEllipse()}) 253 | ``` 254 | 255 | ![](http://matplotlib.org/_images/legend_guide-6.png) 256 | 257 | ## 使用图例的现有示例 258 | 259 | 这里是一个不太详尽的示例列表,涉及以各种方式使用的图例: 260 | 261 | + [`lines_bars_and_markers` 示例代码: `scatter_with_legend.py`](http://matplotlib.org/examples/lines_bars_and_markers/scatter_with_legend.html#lines-bars-and-markers-scatter-with-legend) 262 | + [API 示例代码: `legend_demo.py`](http://matplotlib.org/examples/api/legend_demo.html#api-legend-demo) 263 | + [`pylab_examples` 示例代码: `contourf_hatching.py`](http://matplotlib.org/examples/pylab_examples/contourf_hatching.html#pylab-examples-contourf-hatching) 264 | + [`pylab_examples` 示例代码: `figlegend_demo.py`](http://matplotlib.org/examples/pylab_examples/figlegend_demo.html#pylab-examples-figlegend-demo) 265 | + [`pylab_examples` 示例代码: `finance_work2.py`](http://matplotlib.org/examples/pylab_examples/finance_work2.html#pylab-examples-finance-work2) 266 | + [`pylab_examples` 示例代码: `scatter_symbol.py`](http://matplotlib.org/examples/pylab_examples/scatter_symbol.html#pylab-examples-scatter-symbol) 267 | 268 | ## `matplotlib.pyplot.legend(*args, **kwargs)` 文档 269 | 270 | 在轴域上放置一个图例。 271 | 272 | 为了为轴域上已经存在的线条(例如通过绘图)制作图例,只需使用字符串的可迭代对象(每个图例条目对应一个字符串)调用此函数。 例如: 273 | 274 | ```py 275 | ax.plot([1, 2, 3]) 276 | ax.legend(['A simple line']) 277 | ``` 278 | 279 | 但是,为了使『标签』和图例元素实例保持一致,最好在艺术家创建时指定标签,或者通过调用艺术家的`set_label()`方法: 280 | 281 | ```py 282 | line, = ax.plot([1, 2, 3], label='Inline label') 283 | # 通过调用该方法覆写标签 284 | line.set_label('Label via method') 285 | ax.legend() 286 | ``` 287 | 288 | 通过定义以下划线开头的标签,可以从图例元素自动选择中排除特定线条。 这对于所有艺术家都是默认的,因此不带任何参数调用`legend()`,并且没有手动设置标签会导致没有绘制图例。 289 | 290 | 为了完全控制哪些艺术家拥有图例条目,可以传递拥有图例的艺术家的可迭代对象,然后是相应图例标签的可迭代对象: 291 | 292 | ```py 293 | legend((line1, line2, line3), ('label1', 'label2', 'label3')) 294 | ``` 295 | 296 | ### 参数 297 | 298 | `loc`:整数、字符串或者浮点偶对,默认为`'upper right'`。 299 | 300 | 图例的位置。 可能的代码是: 301 | 302 | |位置字符串 | 位置代码 | 303 | | --- | --- | 304 | | `'best'` | `0` | 305 | | `'upper right'` | `1` | 306 | | `'upper left'` | `2` | 307 | | `'lower left'` | `3` | 308 | | `'lower right'` | `4` | 309 | | `'right'` | `5` | 310 | | `'center left'` | `6` | 311 | | `'center right'` | `7` | 312 | | `'lower center'` | `8` | 313 | | `'upper center'` | `9` | 314 | | `'center'` | `10` | 315 | 316 | 或者,可以是一个二元组,提供图例的距离左下角的`x, y`坐标(在这种情况下,`bbox_to_anchor`将被忽略)。 317 | 318 | `bbox_to_anchor `:`matplotlib.transforms.BboxBase`示例或者浮点元组。 319 | 320 | 在`bbox_transform`坐标(默认轴域坐标)中为图例指定任意位置。 321 | 322 | 例如,要将图例的右上角放在轴域中心,可以使用以下关键字: 323 | 324 | ```py 325 | loc='upper right', bbox_to_anchor=(0.5, 0.5) 326 | ``` 327 | 328 | `ncol`:整数。 329 | 330 | 图例的列数,默认为 1。 331 | 332 | `prop`:`None`、`matplotlib.font_manager.FontProperties`或者字典。 333 | 334 | 图例的字体属性,如果为`None`(默认),会使用当前的` matplotlib.rcParams`。 335 | 336 | `fontsize`:整数、浮点或者`{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}`。 337 | 338 | 控制图例的字体大小。 如果值为数字,则大小将为绝对字体大小(以磅为单位)。 字符串值相对于当前默认字体大小。 此参数仅在未指定`prop`的情况下使用。 339 | 340 | `numpoints`:`None`或者整数。 341 | 342 | 为线条/`matplotlib.lines.Line2D`创建图例条目时,图例中的标记点数。 默认值为`None`,它将从`legend.numpoints` `rcParam`中获取值。 343 | 344 | `scatterpoints`:`None`或者整数。 345 | 346 | 为散点图/`matplotlib.collections.PathCollection`创建图例条目时,图例中的标记点数。 默认值为`None`,它将从`legend.scatterpoints` `rcParam`中获取值。 347 | 348 | `scatteryoffsets`:浮点的可迭代对象。 349 | 350 | 为散点图图例条目创建的标记的垂直偏移量(相对于字体大小)。 0.0 是在图例文本的底部,1.0 是在顶部。 为了将所有标记绘制在相同的高度,请设置为`[0.5]`。 默认值为`[0.375,0.5,0.3125]`。 351 | 352 | `markerscale`:`None`、整数或者浮点。 353 | 354 | 图例标记对于原始绘制的标记的相对大小。 默认值为`None`,它将从`legend.markerscale` `rcParam`中获取值。 355 | 356 | `markerfirst`: `[ True | False ]` 357 | 358 | 如果为`True`,则图例标记位于图例标签的左侧,如果为`False`,图例标记位于图例标签的右侧。 359 | 360 | `frameon`:`None`或布尔值 361 | 362 | 控制是否应在图例周围绘制框架。 默认值为`None`,它将从`legend.frameon` `rcParam`中获取值。 363 | 364 | `fancybox`:`None`或布尔值 365 | 366 | 控制是否应在构成图例背景的`FancyBboxPatch`周围启用圆边。 默认值为`None`,它将从`legend.fancybox` `rcParam`中获取值。 367 | 368 | `shadow`:`None`或布尔值 369 | 370 | 控制是否在图例后面画一个阴影。 默认值为`None`,它将从`legend.shadow` `rcParam`中获取值。 371 | 372 | `framealpha`:`None`或浮点 373 | 374 | 控制图例框架的 Alpha 透明度。 默认值为`None`,它将从`legend.framealpha` `rcParam`中获取值。 375 | 376 | `mode`:`{"expand", None}` 377 | 378 | 如果`mode`设置为`"expand"`,图例将水平扩展来填充轴域区域(如果定义图例的大小,则为`bbox_to_anchor`)。 379 | 380 | `bbox_transform`:`None`或者` matplotlib.transforms.Transform` 381 | 382 | 边界框的变换(`bbox_to_anchor`)。 对于`None`值(默认),将使用`Axes`的`transAxes`变换。 383 | 384 | `title`:字符串或者`None` 385 | 386 | 图例的标题,默认没有标题(`None`)。 387 | 388 | `borderpad`:浮点或`None` 389 | 390 | 图例边框的内边距。 以字体大小为单位度量。 默认值为`None`,它将从`legend.borderpad` `rcParam`中获取值。 391 | 392 | `labelspacing`:浮点或`None` 393 | 394 | 图例条目之间的垂直间距。 以字体大小为单位度量。 默认值为`None`,它将从`legend.labelspacing` `rcParam`中获取值。 395 | 396 | `handlelength`:浮点或`None` 397 | 398 | 图例句柄的长度。 以字体大小为单位度量。 默认值为`None`,它将从`legend.handlelength` `rcParam`取值。 399 | 400 | `handletextpad`:浮点或`None` 401 | 402 | 图例句柄和文本之间的间距。 以字体大小为单位度量。 默认值为`None`,它将从`legend.handletextpad` `rcParam`中获取值。 403 | 404 | `borderaxespad`:浮点或`None` 405 | 406 | 轴和图例边框之间的间距。 以字体大小为单位度量。 默认值为`None`,它将从`legend.borderaxespad` `rcParam`中获取值。 407 | 408 | `columnspacing`:浮点或`None` 409 | 410 | 列间距。以字体大小为单位度量。 默认值为`None`,它将从`legend.columnspacing` `rcParam`中获取值。 411 | 412 | `handler_map`:字典或`None` 413 | 414 | 自定义字典,用于将实例或类型映射到图例处理器。 这个`handler_map`会更新在`matplotlib.legend.Legend.get_legend_handler_map()`中获得的默认处理器字典。 415 | -------------------------------------------------------------------------------- /3.7.md: -------------------------------------------------------------------------------- 1 | # 变换教程 2 | 3 | > 原文:[Transformations Tutorial](http://matplotlib.org/users/transforms_tutorial.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 像任何图形包一样,matplotlib 建立在变换框架之上,以便在坐标系,用户数据坐标系,轴域坐标系,图形坐标系和显示坐标系之间轻易变换。 在 95 %的绘图中,你不需要考虑这一点,因为它发生在背后,但随着你接近自定义图形生成的极限,它有助于理解这些对象,以便可以重用 matplotlib 提供给你的现有变换,或者创建自己的变换(见`matplotlib.transforms`)。 下表总结了现有的坐标系,你应该在该坐标系中使用的变换对象,以及该系统的描述。 在『变换对象』一列中,`ax`是`Axes`实例,`fig`是一个图形实例。 10 | 11 | | 坐标系 | 变换对象 | 描述 | 12 | | --- | --- | --- | 13 | | 数据 | `ax.transData` | 用户数据坐标系,由`xlim`和`ylim`控制 | 14 | | 轴域 | `ax.transAxes` | 轴域坐标系;`(0,0)`是轴域左下角,`(1,1)`是轴域右上角 | 15 | | 图形 | `fig.transFigure` | 图形坐标系;`(0,0)`是图形左下角,`(1,1)`是图形右上角 | 16 | | 显示 | `None` | 这是显示器的像素坐标系; `(0,0)`是显示器的左下角,`(width, height)`是显示器的右上角,以像素为单位。 或者,可以使用恒等变换(`matplotlib.transforms.IdentityTransform()`)来代替`None`。 | 17 | 18 | 上表中的所有变换对象都接受以其坐标系为单位的输入,并将输入变换到显示坐标系。 这就是为什么显示坐标系没有『变换对象』的原因 - 它已经以显示坐标为单位了。 变换也知道如何反转自身,从显示返回自身的坐标系。 这在处理来自用户界面的事件(通常发生在显示空间中),并且你想知道数据坐标系中鼠标点击或按键按下的位置时特别有用。 19 | 20 | ## 数据坐标 21 | 22 | 让我们从最常用的坐标,数据坐标系开始。 每当向轴域添加数据时,matplotlib 会更新数据对象,`set_xlim()`和`set_ylim()`方法最常用于更新。 例如,在下图中,数据的范围在`x`轴上为从 0 到 10,在`y`轴上为从 -1 到 1。 23 | 24 | ```py 25 | import numpy as np 26 | import matplotlib.pyplot as plt 27 | 28 | x = np.arange(0, 10, 0.005) 29 | y = np.exp(-x/2.) * np.sin(2*np.pi*x) 30 | 31 | fig = plt.figure() 32 | ax = fig.add_subplot(111) 33 | ax.plot(x, y) 34 | ax.set_xlim(0, 10) 35 | ax.set_ylim(-1, 1) 36 | 37 | plt.show() 38 | ``` 39 | 40 | ![](http://matplotlib.org/_images/transforms_tutorial-1.png) 41 | 42 | 你可以使用`ax.transData`实例将数据变换为显示坐标系,无论是单个点或是一系列点,如下所示: 43 | 44 | ```py 45 | In [14]: type(ax.transData) 46 | Out[14]: 47 | 48 | In [15]: ax.transData.transform((5, 0)) 49 | Out[15]: array([ 335.175, 247. ]) 50 | 51 | In [16]: ax.transData.transform([(5, 0), (1,2)]) 52 | Out[16]: 53 | array([[ 335.175, 247. ], 54 | [ 132.435, 642.2 ]]) 55 | ``` 56 | 57 | 你可以使用`inverted()`方法创建一个变换,从显示坐标变换为数据坐标: 58 | 59 | ```py 60 | In [41]: inv = ax.transData.inverted() 61 | 62 | In [42]: type(inv) 63 | Out[42]: 64 | 65 | In [43]: inv.transform((335.175, 247.)) 66 | Out[43]: array([ 5., 0.]) 67 | ``` 68 | 69 | 70 | 如果你一直关注本教程,如果你的窗口大小或 dpi 设置不同,显示坐标的确切值可能会有所不同。 同样,在下面的图形中,在 ipython 会话中,由显示标记的点可能并不相同,因为文档图形大小默认值是不同的。 71 | 72 | ![](http://matplotlib.org/_images/annotate_transform.png) 73 | 74 | > 注意 75 | 76 | > 如果在 GUI 后端中运行上述示例中的源代码,你还可能发现数据和显示标注的两个箭头不会指向完全相同的点。 这是因为显示点是在显示图形之前计算的,并且 GUI 后端可以在创建图形时稍微调整图形大小。 如果你自己调整图的大小,效果更明显。 这是你很少想要处理显示空间的一个很好的原因,但是你可以连接到`'on_draw'`事件来更新图上的图坐标;请参阅[事件处理和选择](http://matplotlib.org/users/event_handling.html#event-handling-tutorial)。 77 | 78 | 当你更改轴的`x`或`y`的范围时,将更新数据范围,以便变换生成新的显示点。 注意,当我们只是改变`ylim`,只有`y`显示坐标改变,当我们改变`xlim`也同理。 我们在谈论 [Bbox](http://matplotlib.org/api/transformations.html#matplotlib.transforms.Bbox) 时会深入。 79 | 80 | ```py 81 | In [54]: ax.transData.transform((5, 0)) 82 | Out[54]: array([ 335.175, 247. ]) 83 | 84 | In [55]: ax.set_ylim(-1,2) 85 | Out[55]: (-1, 2) 86 | 87 | In [56]: ax.transData.transform((5, 0)) 88 | Out[56]: array([ 335.175 , 181.13333333]) 89 | 90 | In [57]: ax.set_xlim(10,20) 91 | Out[57]: (10, 20) 92 | 93 | In [58]: ax.transData.transform((5, 0)) 94 | Out[58]: array([-171.675 , 181.13333333]) 95 | ``` 96 | 97 | ## 轴域坐标 98 | 99 | 在数据坐标系之后,轴域可能是第二有用的坐标系。 这里,点`(0,0)`是轴域或子图的左下角,`(0.5,0.5)`是中心,`(1.0,1.0)`是右上角。 你还可以引用范围之外的点,因此`(-0.1,1.1)`位于轴的左上方。 此坐标系在将文本放置在轴中时非常有用,因为你通常需要在固定的位置(例如,轴域窗格的左上角)放置文本气泡,并且在平移或缩放时保持该位置固定。 这里是一个简单的例子,创建四个面板,并将他们标记为`'A'`,`'B'`,`'C'`,`'D'`,你经常在期刊上看到它们。 100 | 101 | ![](http://matplotlib.org/_images/transforms_tutorial-2.png) 102 | 103 | 你也可以在轴坐标系中创建线条或者补丁,但是以我的经验,这比使用`ax.transAxes`放置文本更不实用。 尽管如此,这里是一个愚蠢的例子,它在数据空间中绘制了一些随机点,并且覆盖在一个半透明的圆上面,这个圆以轴域的中心为圆心,半径为轴域的四分之一。 - 如果你的轴域不保留高宽比(见`set_aspect ()`),它将看起来像一个椭圆。 使用平移/缩放工具移动,或手动更改数据的`xlim`和`ylim`,你将看到数据移动,但圆将保持固定,因为它不在数据坐标中,并且将始终保持在轴域的中心 。 104 | 105 | ![](http://matplotlib.org/_images/transforms_tutorial-3.png) 106 | 107 | ## 混合变换 108 | 109 | 在数据与轴域坐标混合的混合坐标空间中绘制是非常实用的,例如创建一个水平跨度,突出`y`数据的一些区域但横跨`x`轴,而无论数据限制,平移或缩放级别等。实际上这些混合线条和跨度非常有用,我们已经内置了一些函数来使它们容易绘制(参见`axhline()`,`axvline()`,`axhspan()`,`axvspan()`),但是为了教学目的,我们使用混合变换实现这里的水平跨度。 这个技巧只适用于可分离的变换,就像你在正常的笛卡尔坐标系中看到的,但不能为不可分离的变换,如`PolarTransform`(极坐标变换)。 110 | 111 | ```py 112 | import numpy as np 113 | import matplotlib.pyplot as plt 114 | import matplotlib.patches as patches 115 | import matplotlib.transforms as transforms 116 | 117 | fig = plt.figure() 118 | ax = fig.add_subplot(111) 119 | 120 | x = np.random.randn(1000) 121 | 122 | ax.hist(x, 30) 123 | ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16) 124 | 125 | # the x coords of this transformation are data, and the 126 | # y coord are axes 127 | trans = transforms.blended_transform_factory( 128 | ax.transData, ax.transAxes) 129 | 130 | # highlight the 1..2 stddev region with a span. 131 | # We want x to be in data coordinates and y to 132 | # span from 0..1 in axes coords 133 | rect = patches.Rectangle((1,0), width=1, height=1, 134 | transform=trans, color='yellow', 135 | alpha=0.5) 136 | 137 | ax.add_patch(rect) 138 | 139 | plt.show() 140 | ``` 141 | 142 | ![](http://matplotlib.org/_images/transforms_tutorial-4.png) 143 | 144 | > 注 145 | 146 | > 混合变换非常有用,其中`x`为数据坐标而`y`为轴域坐标,我们拥有辅助方法来返回内部使用的版本 mpl ,用于绘制`ticks`,`ticklabels`以及其他。方法是`matplotlib.axes.Axes.get_xaxis_transform()`和`matplotlib.axes.Axes.get_yaxis_transform()`。 因此,在上面的示例中,`blended_transform_factory()`的调用可以替换为`get_xaxis_transform`: 147 | 148 | > ```py 149 | > trans = ax.get_xaxis_transform() 150 | > ``` 151 | 152 | ## 使用偏移变换来创建阴影效果 153 | 154 | 变换的一个用法,是创建偏离另一变换的新变换,例如,放置一个对象,相对于另一对象有一些偏移。 通常,你希望物理尺寸上有一些移位,例如以点或英寸,而不是数据坐标为单位,以便移位效果在不同的缩放级别和 dpi 设置下保持不变。 155 | 156 | 偏移的一个用途是创建一个阴影效果,其中你绘制一个与第一个相同的对象,刚好在它的右边和下面,调整`zorder`来确保首先绘制阴影,然后绘制对象,阴影在它之上。 变换模块具有辅助变换`ScaledTranslation`。 它可以这样来实例化: 157 | 158 | ```py 159 | trans = ScaledTranslation(xt, yt, scale_trans) 160 | ``` 161 | 162 | 其中`xt`和`yt`是变换的偏移,`scale_trans`是变换,在应用偏移之前的变换期间缩放`xt`和`yt`。 一个典型的用例是,将图形的`fig.dpi_scale_trans`变换用于`scale_trans`参数,来在实现最终的偏移之前,首先将以点为单位的`xt`和`yt`缩放到显示空间。 163 | DPI 和英寸偏移是常见的用例,我们拥有一个特殊的辅助函数,来在`matplotlib.transforms.offset_copy()`中创建它,它返回一个带有附加偏移的新变换。 但在下面的示例中,我们将自己创建偏移变换。 注意使用加法运算符: 164 | 165 | ```py 166 | offset = transforms.ScaledTranslation(dx, dy, 167 | fig.dpi_scale_trans) 168 | shadow_transform = ax.transData + offset 169 | ``` 170 | 171 | 这里显示了,可以使用加法运算符将变换链起来。 该代码表示:首先应用数据变换`ax.transData`,然后由`dx`和`dy`点翻译数据。 在[排版](https://en.wikipedia.org/wiki/Point_%28typography%29)中,一个点是 1/72 英寸,通过以点为单位指定偏移,你的图形看起来是一样的,无论所保存的 dpi 分辨率。 172 | 173 | ```py 174 | import numpy as np 175 | import matplotlib.pyplot as plt 176 | import matplotlib.patches as patches 177 | import matplotlib.transforms as transforms 178 | 179 | fig = plt.figure() 180 | ax = fig.add_subplot(111) 181 | 182 | # make a simple sine wave 183 | x = np.arange(0., 2., 0.01) 184 | y = np.sin(2*np.pi*x) 185 | line, = ax.plot(x, y, lw=3, color='blue') 186 | 187 | # shift the object over 2 points, and down 2 points 188 | dx, dy = 2/72., -2/72. 189 | offset = transforms.ScaledTranslation(dx, dy, 190 | fig.dpi_scale_trans) 191 | shadow_transform = ax.transData + offset 192 | 193 | # now plot the same data with our offset transform; 194 | # use the zorder to make sure we are below the line 195 | ax.plot(x, y, lw=3, color='gray', 196 | transform=shadow_transform, 197 | zorder=0.5*line.get_zorder()) 198 | 199 | ax.set_title('creating a shadow effect with an offset transform') 200 | plt.show() 201 | ``` 202 | 203 | ![](http://matplotlib.org/_images/transforms_tutorial-5.png) 204 | 205 | ## 变换流水线 206 | 207 | 我们在本教程中一直使用的`ax.transData`变换是三种不同变换的组合,它们构成从数据到显示坐标的变换流水线。 Michael Droettboom 实现了变换框架,提供了一个干净的 API,它隔离了在极坐标和对数坐标图中发生的非线性投影和尺度,以及在平移和缩放时发生的线性仿射变换。 这里有一个效率问题,因为你可以平移和放大你的轴域,它会影响仿射变换,但你可能不需要计算潜在的昂贵的非线性比例或简单的导航事件的投影。 也可以将仿射变换矩阵相乘在一起,然后在一步之中将它们应用于坐标。 这对所有可能的变换不都是有效的。 208 | 209 | 这里是在`ax.transData`实例在基本可分离的`Axes`类中的定义方式。 210 | 211 | ```py 212 | self.transData = self.transScale + (self.transLimits + self.transAxes) 213 | ``` 214 | 215 | 我们已经在`Axes`坐标中引入了上面的`transAxes`实例,它将轴或子图边界框的`(0,0)`,`(1,1)`角映射到显示空间,所以让我们看看这两个部分。 216 | 217 | `self.transLimits`是从数据到轴域坐标的变换; 也就是说,它将你的视图`xlim`和`ylim`映射到轴域单位空间(然后`transAxes`将该单位空间用于显示空间)。 我们可以在这里看到这一点: 218 | 219 | ```py 220 | In [80]: ax = subplot(111) 221 | 222 | In [81]: ax.set_xlim(0, 10) 223 | Out[81]: (0, 10) 224 | 225 | In [82]: ax.set_ylim(-1,1) 226 | Out[82]: (-1, 1) 227 | 228 | In [84]: ax.transLimits.transform((0,-1)) 229 | Out[84]: array([ 0., 0.]) 230 | 231 | In [85]: ax.transLimits.transform((10,-1)) 232 | Out[85]: array([ 1., 0.]) 233 | 234 | In [86]: ax.transLimits.transform((10,1)) 235 | Out[86]: array([ 1., 1.]) 236 | 237 | In [87]: ax.transLimits.transform((5,0)) 238 | Out[87]: array([ 0.5, 0.5]) 239 | ``` 240 | 241 | 而且我们可以使用相同的反转变换,从轴域单位坐标变换回数据坐标。 242 | 243 | ```py 244 | In [90]: inv.transform((0.25, 0.25)) 245 | Out[90]: array([ 2.5, -0.5]) 246 | ``` 247 | 248 | 最后一个是`self.transScale`属性,它负责数据的可选非线性缩放,例如对数轴域。 当`Axes`初始化时,这只是设置为恒等变换,因为基本的 matplotlib 轴域具有线性缩放,但是当你调用对数缩放函数如`semilogx()`或使用`set_xscale`显式设置为对数时,`ax.transScale`属性为处理非线性投影而设置。 缩放变换是相应`xaxis`和`yaxis` 的`Axis`实例的属性。 例如,当调用`ax.set_xscale('log')`时,`xaxis`会将其缩放更新为`matplotlib.scale.LogScale`实例。 249 | 250 | 对于不可分离的轴域,`PolarAxes`,还有一个要考虑的部分,投影变换。 `matplotlib.projections.polar.PolarAxes`的`transData`类似于典型的可分离 matplotlib 轴域,带有一个额外的部分,`transProjection`: 251 | 252 | 253 | ```py 254 | self.transData = self.transScale + self.transProjection + \ 255 | (self.transProjectionAffine + self.transAxes) 256 | ``` 257 | 258 | `transProjection`将来自空间的投影,例如,地图数据的纬度和经度,或极坐标数据的半径和极角,处理为可分离的笛卡尔坐标系。 在`matplotlib.projections`包中有几个投影示例,深入了解的最好方法是打开这些包的源代码,看看如何自己制作它,因为 matplotlib 支持可扩展的轴域和投影。 Michael Droettboom 提供了一个创建一个锤投影轴域的很好的教程示例;请参阅 api 示例代码:[`custom_projection_example.py`](http://matplotlib.org/examples/api/custom_projection_example.html#api-custom-projection-example)。 259 | -------------------------------------------------------------------------------- /3.8.md: -------------------------------------------------------------------------------- 1 | # 路径教程 2 | 3 | > 原文:[Path Tutorial](http://matplotlib.org/users/path_tutorial.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 位于所有`matplotlib.patch`对象底层的对象是`Path`,它支持`moveto`,`lineto`,`curveto`命令的标准几个,来绘制由线段和样条组成的简单和复合轮廓。 路径由`(x,y)`顶点的`(N,2)`数组,以及路径代码的长度为 N 的数组实例化。 例如,为了绘制`(0,0)`到`(1,1)`的单位矩形,我们可以使用这个代码: 10 | 11 | ```py 12 | import matplotlib.pyplot as plt 13 | from matplotlib.path import Path 14 | import matplotlib.patches as patches 15 | 16 | verts = [ 17 | (0., 0.), # left, bottom 18 | (0., 1.), # left, top 19 | (1., 1.), # right, top 20 | (1., 0.), # right, bottom 21 | (0., 0.), # ignored 22 | ] 23 | 24 | codes = [Path.MOVETO, 25 | Path.LINETO, 26 | Path.LINETO, 27 | Path.LINETO, 28 | Path.CLOSEPOLY, 29 | ] 30 | 31 | path = Path(verts, codes) 32 | 33 | fig = plt.figure() 34 | ax = fig.add_subplot(111) 35 | patch = patches.PathPatch(path, facecolor='orange', lw=2) 36 | ax.add_patch(patch) 37 | ax.set_xlim(-2,2) 38 | ax.set_ylim(-2,2) 39 | plt.show() 40 | ``` 41 | 42 | ![](http://matplotlib.org/_images/path_tutorial-1.png) 43 | 44 | 下面的路径代码会被接受: 45 | 46 | 47 | | 代码 | 顶点 | 描述 | 48 | | --- | --- | 49 | | `STOP` | 1 (被忽略) | 标志整个路径终点的标记(当前不需要或已忽略) | 50 | | `MOVETO` | 1 | 提起笔并移动到指定顶点 | 51 | | `LINETO` | 1 | 从当前位置向指定顶点画线 | 52 | | `CURVE3` | 2 (一个控制点,一个终点) | 从当前位置,以给定控制点向给定端点画贝塞尔曲线 | 53 | | `CURVE4` | 3 (两个控制点,一个终点) | 从当前位置,以给定控制点向给定端点画三次贝塞尔曲线 | 54 | | `CLOSEPOLY` | 1 (点自身被忽略) | 向当前折线的起点画线 | 55 | 56 | ## 贝塞尔示例 57 | 58 | 一些路径组件需要以多个顶点来指定:例如`CURVE3`是具有一个控制点和一个端点的贝塞尔曲线,`CURVE4`具有用做两个控制点和端点的三个顶点。 下面的示例显示了`CURVE4`贝塞尔曲线 - 贝塞尔曲线将包含在起始点,两个控制点和终点的凸包中: 59 | 60 | ```py 61 | import matplotlib.pyplot as plt 62 | from matplotlib.path import Path 63 | import matplotlib.patches as patches 64 | 65 | verts = [ 66 | (0., 0.), # P0 67 | (0.2, 1.), # P1 68 | (1., 0.8), # P2 69 | (0.8, 0.), # P3 70 | ] 71 | 72 | codes = [Path.MOVETO, 73 | Path.CURVE4, 74 | Path.CURVE4, 75 | Path.CURVE4, 76 | ] 77 | 78 | path = Path(verts, codes) 79 | 80 | fig = plt.figure() 81 | ax = fig.add_subplot(111) 82 | patch = patches.PathPatch(path, facecolor='none', lw=2) 83 | ax.add_patch(patch) 84 | 85 | xs, ys = zip(*verts) 86 | ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10) 87 | 88 | ax.text(-0.05, -0.05, 'P0') 89 | ax.text(0.15, 1.05, 'P1') 90 | ax.text(1.05, 0.85, 'P2') 91 | ax.text(0.85, -0.05, 'P3') 92 | 93 | ax.set_xlim(-0.1, 1.1) 94 | ax.set_ylim(-0.1, 1.1) 95 | plt.show() 96 | ``` 97 | 98 | ![](http://matplotlib.org/_images/path_tutorial-2.png) 99 | 100 | ## 复合路径 101 | 102 | 所有在 matplotlib,Rectangle,Circle,Polygon 等中的简单补丁原语都是用简单的路径实现的。通过使用复合路径,通常可以更有效地实现绘制函数,如`hist()`和`bar()`,它们创建了许多原语,例如一堆`Rectangle`,通常可使用复合路径来实现。`bar`创建一个矩形列表,而不是一个复合路径,很大程度上出于历史原因:路径代码是比较新的,`bar `在它之前就存在。虽然我们现在可以改变它,但它会破坏旧的代码,所以如果你需要为了效率,在你自己的代码中这样做,例如,创建动画条形图,在这里我们将介绍如何创建复合路径,替换`bar`中的功能。 103 | 104 | 我们将通过为每个直方图的条形创建一系列矩形,来创建直方图图表:矩形宽度是条形的宽度,矩形高度是该条形中的数据点数量。首先,我们将创建一些随机的正态分布数据并计算直方图。因为 numpy 返回条形边缘而不是中心,所以下面的示例中`bins`的长度比`n`的长度大 1: 105 | 106 | ```py 107 | # histogram our data with numpy 108 | data = np.random.randn(1000) 109 | n, bins = np.histogram(data, 100) 110 | ``` 111 | 112 | 我们现在将提取矩形的角。 下面的每个`left`,`bottom`等数组长度为`len(n)`,其中`n`是每个直方图条形的计数数组: 113 | 114 | ```py 115 | # get the corners of the rectangles for the histogram 116 | left = np.array(bins[:-1]) 117 | right = np.array(bins[1:]) 118 | bottom = np.zeros(len(left)) 119 | top = bottom + n 120 | ``` 121 | 122 | 现在我们必须构造复合路径,它由每个矩形的一系列`MOVETO`,`LINETO`和`CLOSEPOLY`组成。 对于每个矩形,我们需要 5 个顶点:一个代表`MOVETO`,三个代表`LINETO`,一个代表`CLOSEPOLY`。 如上表所示,`closepoly`的顶点被忽略,但我们仍然需要它来保持代码与顶点对齐: 123 | 124 | ```py 125 | nverts = nrects*(1+3+1) 126 | verts = np.zeros((nverts, 2)) 127 | codes = np.ones(nverts, int) * path.Path.LINETO 128 | codes[0::5] = path.Path.MOVETO 129 | codes[4::5] = path.Path.CLOSEPOLY 130 | verts[0::5,0] = left 131 | verts[0::5,1] = bottom 132 | verts[1::5,0] = left 133 | verts[1::5,1] = top 134 | verts[2::5,0] = right 135 | verts[2::5,1] = top 136 | verts[3::5,0] = right 137 | verts[3::5,1] = bottom 138 | ``` 139 | 140 | 剩下的就是创建路径了,将其添加到`PathPatch`,将其添加到我们的轴域: 141 | 142 | ```py 143 | barpath = path.Path(verts, codes) 144 | patch = patches.PathPatch(barpath, facecolor='green', 145 | edgecolor='yellow', alpha=0.5) 146 | ax.add_patch(patch) 147 | ``` 148 | 149 | 结果为: 150 | 151 | ![](http://matplotlib.org/_images/compound_path_demo.png) 152 | -------------------------------------------------------------------------------- /3.9.md: -------------------------------------------------------------------------------- 1 | # 路径效果指南 2 | 3 | > 原文:[Path effects guide](http://matplotlib.org/users/patheffects_guide.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | Matplotlib 的`patheffects`模块提供了一些功能,用于将多个绘制层次应用到任何艺术家,并可以通过路径呈现。 10 | 11 | 可以对其应用路径效果的艺术家包括`Patch`,`Line2D`,`Collection`,甚至文本。 每个艺术家的路径效果都可以通过`set_path_effects`方法(`set_path_effects`)控制,它需要一个`AbstractPathEffect`的可迭代实例。 12 | 13 | 最简单的路径效果是普通效果,它简单地绘制艺术家,并没有任何效果: 14 | 15 | ```py 16 | import matplotlib.pyplot as plt 17 | import matplotlib.patheffects as path_effects 18 | 19 | fig = plt.figure(figsize=(5, 1.5)) 20 | text = fig.text(0.5, 0.5, 'Hello path effects world!\nThis is the normal ' 21 | 'path effect.\nPretty dull, huh?', 22 | ha='center', va='center', size=20) 23 | text.set_path_effects([path_effects.Normal()]) 24 | plt.show() 25 | ``` 26 | 27 | ![](http://matplotlib.org/_images/patheffects_guide-1.png) 28 | 29 | ## 添加阴影 30 | 31 | 比正常效果更有趣的路径效果是阴影,我们可以应用于任何基于路径的艺术家。 `SimplePatchShadow`和`SimpleLineShadow`类通过在基本艺术家下面绘制填充补丁或线条补丁来实现它: 32 | 33 | ```py 34 | import matplotlib.pyplot as plt 35 | import matplotlib.patheffects as path_effects 36 | 37 | text = plt.text(0.5, 0.5, 'Hello path effects world!', 38 | path_effects=[path_effects.withSimplePatchShadow()]) 39 | 40 | plt.plot([0, 3, 2, 5], linewidth=5, color='blue', 41 | path_effects=[path_effects.SimpleLineShadow(), 42 | path_effects.Normal()]) 43 | plt.show() 44 | ``` 45 | 46 | ![](http://matplotlib.org/_images/patheffects_guide-2.png) 47 | 48 | 请注意本示例中设置路径效果的两种方法。 第一个使用`with *`类,来包含“正常”效果之后的所需功能,而后者明确定义要绘制的两个路径效果。 49 | 50 | ## 让艺术家脱颖而出 51 | 52 | 使艺术家在视觉上脱颖而出的一个好方法是,在实际艺术家下面以粗体颜色绘制轮廓。 `Stroke`路径效果使其相对简单: 53 | 54 | ```py 55 | import matplotlib.pyplot as plt 56 | import matplotlib.patheffects as path_effects 57 | 58 | fig = plt.figure(figsize=(7, 1)) 59 | text = fig.text(0.5, 0.5, 'This text stands out because of\n' 60 | 'its black border.', color='white', 61 | ha='center', va='center', size=30) 62 | text.set_path_effects([path_effects.Stroke(linewidth=3, foreground='black'), 63 | path_effects.Normal()]) 64 | plt.show() 65 | ``` 66 | 67 | ![](http://matplotlib.org/_images/patheffects_guide-3.png) 68 | 69 | 70 | 重要的是注意,这种效果能够工作,因为我们已经绘制两次文本路径:一次使用粗黑线,然后另一次使用原始文本路径在上面绘制。 71 | 72 | 您可能已经注意到,`Stroke`、`SimplePatchShadow`和`SimpleLineShadow`的关键字不是通常的`Artist`关键字(例如`facecolor`和`edgecolor`等)。这是因为使用这些路径效果,我们操作了 matplotlib 的较低层。实际上,接受的关键字是用于`matplotlib.backend_bases.GraphicsContextBase`实例的关键字,它们为易于创建新的后端而设计,而不是用于其用户界面。 73 | 74 | ## 对路径效果艺术家的更大控制 75 | 76 | 如前所述,一些路径效果的操作级别低于大多数用户操作,这意味着设置关键字(如`facecolor`和`edgecolor`)会导致`AttributeError`。幸运的是,有一个通用的`PathPatchEffect`路径效果,它创建一个具有原始路径的`PathPatch`类。此效果的关键字与`PathPatch`相同: 77 | 78 | ```py 79 | import matplotlib.pyplot as plt 80 | import matplotlib.patheffects as path_effects 81 | 82 | fig = plt.figure(figsize=(8, 1)) 83 | t = fig.text(0.02, 0.5, 'Hatch shadow', fontsize=75, weight=1000, va='center') 84 | t.set_path_effects([path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx', 85 | facecolor='gray'), 86 | path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1, 87 | facecolor='black')]) 88 | plt.show() 89 | ``` 90 | 91 | ![](http://matplotlib.org/_images/patheffects_guide-4.png) 92 | -------------------------------------------------------------------------------- /3.md: -------------------------------------------------------------------------------- 1 | # 教程 2 | 3 | -------------------------------------------------------------------------------- /4.1.md: -------------------------------------------------------------------------------- 1 | # 引言 2 | 3 | > 原文:[Text introduction](http://matplotlib.org/users/text_intro.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | matplotlib 具有优秀的文本支持,包括数学表达式,光栅和向量输出的 truetype 支持,任意旋转的换行分隔文本和 unicode 支持。 因为我们直接在输出文档中嵌入字体,例如 postscript 或 PDF,你在屏幕上看到的也是你在打印件中得到的。 freetype2 可产生非常漂亮,抗锯齿的字体,即使在小光栅尺寸下看起来也不错。 matplotlib 拥有自己的`matplotlib.font_manager`,感谢 Paul Barrett,他实现了一个跨平台,符合 W3C 标准的字体查找算法。 10 | 11 | 你可以完全控制每个文本属性(字体大小,字体重量,文本位置和颜色等),并在`rc`文件中设置合理的默认值。 并且对于那些对数学或科学图像感兴趣的人,matplotlib 实现了大量的 TeX 数学符号和命令,来支持你图中任何地方放置数学表达式。 -------------------------------------------------------------------------------- /4.2.md: -------------------------------------------------------------------------------- 1 | # 基本的文本命令 2 | 3 | > 原文:[Basic text commands](http://matplotlib.org/users/text_intro.html#basic-text-commands) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | ## text 10 | 11 | 12 | 在`Axes`的任意位置添加文本。 13 | 14 | 命令式:[`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)。 15 | 16 | 17 | ## xlabel 18 | 19 | 向 x 轴添加轴标签。 20 | 21 | 命令式:[`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)。 22 | 23 | ## ylabel 24 | 25 | 向 y 轴添加轴标签。 26 | 27 | 命令式:[`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)。 28 | 29 | ## title 30 | 31 | 向`Axes`添加标题。 32 | 33 | 命令式:[`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)。 34 | 35 | ## figtext 36 | 37 | 向`Figure`的任意位置添加文本。 38 | 39 | 命令式:[`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)。 40 | 41 | ## suptitle 42 | 43 | 向`Figure`添加标题。 44 | 45 | 命令式:[`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)。 46 | 47 | ## annotate 48 | 49 | 向`Axes`添加标注,带有可选的箭头。 50 | 51 | 命令式:[`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)。 52 | 53 | 所有这些函数创建并返回一个`matplotlib.text.Text()`实例,它可以配置各种字体和其他属性。 下面的示例在实战中展示所有这些命令。 54 | 55 | ```py 56 | # -*- coding: utf-8 -*- 57 | import matplotlib.pyplot as plt 58 | 59 | fig = plt.figure() 60 | fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold') 61 | 62 | ax = fig.add_subplot(111) 63 | fig.subplots_adjust(top=0.85) 64 | ax.set_title('axes title') 65 | 66 | ax.set_xlabel('xlabel') 67 | ax.set_ylabel('ylabel') 68 | 69 | ax.text(3, 8, 'boxed italics text in data coords', style='italic', 70 | bbox={'facecolor':'red', 'alpha':0.5, 'pad':10}) 71 | 72 | ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) 73 | 74 | ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik') 75 | 76 | ax.text(0.95, 0.01, 'colored text in axes coords', 77 | verticalalignment='bottom', horizontalalignment='right', 78 | transform=ax.transAxes, 79 | color='green', fontsize=15) 80 | 81 | 82 | ax.plot([2], [1], 'o') 83 | ax.annotate('annotate', xy=(2, 1), xytext=(3, 4), 84 | arrowprops=dict(facecolor='black', shrink=0.05)) 85 | 86 | ax.axis([0, 10, 0, 10]) 87 | 88 | plt.show() 89 | ``` 90 | 91 | ![](http://matplotlib.org/_images/text_commands.png) -------------------------------------------------------------------------------- /4.3.md: -------------------------------------------------------------------------------- 1 | # 文本属性及布局 2 | 3 | > 原文:[Text properties and layout](http://matplotlib.org/users/text_props.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | `matplotlib.text.Text`实例有各种属性,可以通过关键字参数配置文本命令(例如,`title()`,`xlabel()`和`text()`)。 10 | 11 | 12 | | 属性 | 值类型 | 13 | | --- | --- | 14 | | alpha | 浮点 | 15 | | backgroundcolor | 任何 matplotlib 颜色 | 16 | | bbox | rectangle prop dict plus key 'pad' which is a pad in points | 17 | | clip_box | `matplotlib.transform.Bbox` 实例 | 18 | | clip_on | `[True / False]` | 19 | | clip_path | `Path`,`Transform`或`Patch` 实例 | 20 | | color | 任何 matplotlib 颜色 | 21 | | family | `[ 'serif' / 'sans-serif' / 'cursive' / 'fantasy' / 'monospace' ]` | 22 | | fontproperties | `matplotlib.font_manager.FontProperties` 实例 | 23 | | horizontalalignment or ha | `[ 'center' / 'right' / 'left' ]` | 24 | | label | 任何字符串 | 25 | | linespacing | 浮点 | 26 | | multialignment | `['left' / 'right' / 'center' ]` | 27 | | name or fontname | 字符串,例如 `['Sans' / 'Courier' / 'Helvetica' ...]` | 28 | | picker | [`None` / 浮点 / 布尔值 / 可调用对象]` | 29 | | position | `(x,y)` | 30 | | rotation | [ 角度制的角度 / 'vertical' / 'horizontal' | 31 | | size or fontsize | [ 点的尺寸 | 相对尺寸,例如 `['smaller', 'x-large' ]` | 32 | | style or fontstyle | `[ 'normal' / 'italic' / 'oblique']` | 33 | | text | 字符串或任何可使用`'%s'`打印的东西 | 34 | | transform | `matplotlib.transform` 实例 | 35 | | variant | `[ 'normal' / 'small-caps' ]` | 36 | | verticalalignment or va | `[ 'center' / 'top' / 'bottom' / 'baseline' ]` | 37 | | visible | `[True / False]` | 38 | | weight or fontweight | `[ 'normal' / 'bold' / 'heavy' / 'light' / 'ultrabold' / 'ultralight']` | 39 | | x | 浮点 | 40 | | y | 浮点 | 41 | | zorder | 任意数值 | 42 | 43 | 你可以使用对齐参数`horizontalalignment`,`verticalalignment`和`multialignment`来布置文本。 `horizontalalignment`控制文本的`x`位置参数表示文本边界框的左边,中间或右边。 `verticalalignment`控制文本的`y`位置参数表示文本边界框的底部,中心或顶部。 `multialignment`,仅对于换行符分隔的字符串,控制不同的行是左,中还是右对齐。 这里是一个使用`text()`命令显示各种对齐方式的例子。 在整个代码中使用`transform = ax.transAxes`,表示坐标相对于轴边界框给出,其中`0,0`是轴的左下角,`1,1`是右上角。 44 | 45 | ```py 46 | import matplotlib.pyplot as plt 47 | import matplotlib.patches as patches 48 | 49 | # build a rectangle in axes coords 50 | left, width = .25, .5 51 | bottom, height = .25, .5 52 | right = left + width 53 | top = bottom + height 54 | 55 | fig = plt.figure() 56 | ax = fig.add_axes([0,0,1,1]) 57 | 58 | # axes coordinates are 0,0 is bottom left and 1,1 is upper right 59 | p = patches.Rectangle( 60 | (left, bottom), width, height, 61 | fill=False, transform=ax.transAxes, clip_on=False 62 | ) 63 | 64 | ax.add_patch(p) 65 | 66 | ax.text(left, bottom, 'left top', 67 | horizontalalignment='left', 68 | verticalalignment='top', 69 | transform=ax.transAxes) 70 | 71 | ax.text(left, bottom, 'left bottom', 72 | horizontalalignment='left', 73 | verticalalignment='bottom', 74 | transform=ax.transAxes) 75 | 76 | ax.text(right, top, 'right bottom', 77 | horizontalalignment='right', 78 | verticalalignment='bottom', 79 | transform=ax.transAxes) 80 | 81 | ax.text(right, top, 'right top', 82 | horizontalalignment='right', 83 | verticalalignment='top', 84 | transform=ax.transAxes) 85 | 86 | ax.text(right, bottom, 'center top', 87 | horizontalalignment='center', 88 | verticalalignment='top', 89 | transform=ax.transAxes) 90 | 91 | ax.text(left, 0.5*(bottom+top), 'right center', 92 | horizontalalignment='right', 93 | verticalalignment='center', 94 | rotation='vertical', 95 | transform=ax.transAxes) 96 | 97 | ax.text(left, 0.5*(bottom+top), 'left center', 98 | horizontalalignment='left', 99 | verticalalignment='center', 100 | rotation='vertical', 101 | transform=ax.transAxes) 102 | 103 | ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle', 104 | horizontalalignment='center', 105 | verticalalignment='center', 106 | fontsize=20, color='red', 107 | transform=ax.transAxes) 108 | 109 | ax.text(right, 0.5*(bottom+top), 'centered', 110 | horizontalalignment='center', 111 | verticalalignment='center', 112 | rotation='vertical', 113 | transform=ax.transAxes) 114 | 115 | ax.text(left, top, 'rotated\nwith newlines', 116 | horizontalalignment='center', 117 | verticalalignment='center', 118 | rotation=45, 119 | transform=ax.transAxes) 120 | 121 | ax.set_axis_off() 122 | plt.show() 123 | ``` 124 | 125 | ![](http://matplotlib.org/_images/text_layout.png) 126 | -------------------------------------------------------------------------------- /4.4.md: -------------------------------------------------------------------------------- 1 | # 默认字体 2 | 3 | > 原文:[Text properties and layout](http://matplotlib.org/users/text_props.html#default-font) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 基本的默认字体由一系列`rcParams`参数控制: 10 | 11 | | `rcParam` | 用法 | 12 | | --- | --- | 13 | | `'font.family'` | 字体名称或`{'cursive', 'fantasy', 'monospace', 'sans', 'sans serif', 'sans-serif', 'serif'}`的列表 | 14 | | `'font.style'` | 默认字体,例如`'normal'`,`'italic'` | 15 | | `'font.variant'` | 默认变体,例如`'normal'`,`'small-caps'`(未测试) | 16 | | `'font.stretch'` | 默认拉伸`'normal'`,`'condensed'`(未完成) | 17 | | `'font.weight'` | 字体粗细,可为整数或字符串 | 18 | | `'font.size'` | 默认字体大小(以磅为单位)。 相对字体大小(`'large'`,`'x-small'`)按照该大小计算 | 19 | 20 | 字体系列别名(`{'cursive','fantasy','monospace','sans','sans serif','sans-serif','serif'}`)和实际字体名称之间的映射由以下`rcParams`控制 : 21 | 22 | 23 | | 系列别名 | 映射的`rcParam` | 24 | | --- | --- | 25 | | `'serif'` | `'font.serif'` | 26 | | `'monospace'` | `'font.monospace'` | 27 | | `'fantasy'` | `'font.fantasy'` | 28 | | `'cursive'` | `'font.cursive'` | 29 | | `{'sans', 'sans serif', 'sans-serif'}` | `'font.sans-serif'` | 30 | 31 | 它是字体名称的列表。 32 | 33 | ## 非拉丁字形文本 34 | 35 | 从 v2.0 开始,[默认字体](http://matplotlib.org/users/dflt_style_changes.html#default-changes-font)包含许多西方字母的字形,但仍然没有覆盖 mpl 用户可能需要的所有字形。 例如,DejaVu 没有覆盖中文,韩语或日语。 36 | 37 | 要将默认字体设置为支持所需代码点的字体,请将字体名称添加到`font.family`或所需的别名列表前面。 38 | 39 | ```py 40 | matplotlib.rcParams['font.sans-serif'] = ['Source Han Sans TW', 'sans-serif'] 41 | ``` 42 | 43 | 或在`.matplotlibrc`文件中设置: 44 | 45 | ```py 46 | font.sans-serif: Source Han Sans TW, Ariel, sans-serif 47 | ``` 48 | 49 | 要控制每个艺术家使用的字体,使用上面记录的`'name'`,`'fontname'`或`'fontproperties'`关键字参数。 50 | 51 | 在 linux 上,`fc-list`是用于发现字体名称的实用工具;例如 52 | 53 | ``` 54 | $ fc-list :lang=zh family 55 | Noto to Sans Mono CJK TC,Noto Sans Mono CJK TC Bold 56 | Noto Sans CJK TC,Noto Sans CJK TC Medium 57 | Noto Sans CJK TC,Noto Sans CJK TC DemiLight 58 | Noto Sans CJK KR,Noto Sans CJK KR Black 59 | Noto Sans CJK TC,Noto Sans CJK TC Black 60 | Noto Sans Mono CJK TC,Noto Sans Mono CJK TC Regular 61 | Noto Sans CJK SC,Noto Sans CJK SC Light 62 | ``` 63 | 64 | 列出了所有支持中文的字体。 65 | -------------------------------------------------------------------------------- /4.5.md: -------------------------------------------------------------------------------- 1 | # 标注 2 | 3 | > 原文:[Annotation](http://matplotlib.org/users/annotations.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | ## 基本标注 10 | 11 | 使用`text()`会将文本放置在轴域的任意位置。 文本的一个常见用例是标注绘图的某些特征,而`annotate()`方法提供辅助函数,使标注变得容易。 在标注中,有两个要考虑的点:由参数`xy`表示的标注位置和`xytext`的文本位置。 这两个参数都是`(x, y)`元组。 12 | 13 | ```py 14 | import numpy as np 15 | import matplotlib.pyplot as plt 16 | 17 | fig = plt.figure() 18 | ax = fig.add_subplot(111) 19 | 20 | t = np.arange(0.0, 5.0, 0.01) 21 | s = np.cos(2*np.pi*t) 22 | line, = ax.plot(t, s, lw=2) 23 | 24 | ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), 25 | arrowprops=dict(facecolor='black', shrink=0.05), 26 | ) 27 | 28 | ax.set_ylim(-2,2) 29 | plt.show() 30 | ``` 31 | 32 | [源代码](http://matplotlib.org/mpl_examples/pyplots/annotation_basic.py) 33 | 34 | ![](http://matplotlib.org/_images/annotation_basic.png) 35 | 36 | 在该示例中,`xy`(箭头尖端)和`xytext`位置(文本位置)都以数据坐标为单位。 有多种可以选择的其他坐标系 - 你可以使用`xycoords`和`textcoords`以及下列字符串之一(默认为`data`)指定`xy`和`xytext`的坐标系。 37 | 38 | | 参数 | 坐标系 | 39 | | `'figure points'` | 距离图形左下角的点数量 | 40 | | `'figure pixels'` | 距离图形左下角的像素数量 | 41 | | `'figure fraction'` | 0,0 是图形左下角,1,1 是右上角 | 42 | | `'axes points'` | 距离轴域左下角的点数量 | 43 | | `'axes pixels'` | 距离轴域左下角的像素数量 | 44 | | `'axes fraction'` | 0,0 是轴域左下角,1,1 是右上角 | 45 | | `'data'` | 使用轴域数据坐标系 | 46 | 47 | 例如将文本以轴域小数坐标系来放置,我们可以: 48 | 49 | ```py 50 | ax.annotate('local max', xy=(3, 1), xycoords='data', 51 | xytext=(0.8, 0.95), textcoords='axes fraction', 52 | arrowprops=dict(facecolor='black', shrink=0.05), 53 | horizontalalignment='right', verticalalignment='top', 54 | ) 55 | ``` 56 | 57 | 对于物理坐标系(点或像素),原点是图形或轴的左下角。 58 | 59 | 或者,你可以通过在可选关键字参数`arrowprops`中提供箭头属性字典来绘制从文本到注释点的箭头。 60 | 61 | 62 | | `arrowprops`键 | 描述 | 63 | | --- | --- | 64 | | `width` | 箭头宽度,以点为单位 | 65 | | `frac` | 箭头头部所占据的比例 | 66 | | `headwidth` | 箭头的底部的宽度,以点为单位 | 67 | | `shrink` | 移动提示,并使其离注释点和文本一些距离 | 68 | | `**kwargs` | `matplotlib.patches.Polygon`的任何键,例如`facecolor` | 69 | 70 | 在下面的示例中,`xy`点是原始坐标(`xycoords`默认为`'data'`)。 对于极坐标轴,它在`(theta, radius)`空间中。 此示例中的文本放置在图形小数坐标系中。 `matplotlib.text.Text`关键字`args`,例如`horizontalalignment`,`verticalalignment`和`fontsize`,从`annotate`传给`Text`实例。 71 | 72 | [源代码](http://matplotlib.org/mpl_examples/pyplots/annotation_polar.py) 73 | 74 | ![](http://matplotlib.org/_images/annotation_polar.png) 75 | 76 | 注释(包括花式箭头)的所有高上大的内容的更多信息,请参阅[高级标注](http://matplotlib.org/users/annotations.html#plotting-guide-annotation)和[`pylab_examples`示例代码:`annotation_demo.py`](http://matplotlib.org/examples/pylab_examples/annotation_demo.html#pylab-examples-annotation-demo)。 77 | 78 | 不要继续,除非你已经阅读了[基本标注](http://matplotlib.org/users/annotations.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)。 79 | 80 | ## 高级标注 81 | 82 | ### 使用框和文本来标注 83 | 84 | 让我们以一个简单的例子来开始。 85 | 86 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_text_arrow.py) 87 | 88 | ![](http://matplotlib.org/_images/annotate_text_arrow.png) 89 | 90 | 在`pyplot`模块(或`Axes`类的`text`方法)中的`text()`函数接受`bbox`关键字参数,并且在提供时,在文本周围绘制一个框。 91 | 92 | 与文本相关联的补丁对象可以通过以下方式访问: 93 | 94 | ```py 95 | bb = t.get_bbox_patch() 96 | ``` 97 | 98 | 返回值是`FancyBboxPatch`的一个实例,并且补丁属性(如`facecolor`,`edgewidth`等)可以像平常一样访问和修改。 为了更改框的形状,请使用`set_boxstyle`方法。 99 | 100 | ```py 101 | bb.set_boxstyle("rarrow", pad=0.6) 102 | ``` 103 | 104 | 该参数是框样式的名称与其作为关键字参数的属性。 目前,实现了以下框样式。 105 | 106 | | 类 | 名称 | 属性 | 107 | | --- | --- | 108 | | Circle | `circle` | `pad=0.3` | 109 | | DArrow | `darrow` | `pad=0.3` | 110 | | LArrow | `larrow` | `pad=0.3` | 111 | | RArrow | `rarrow` | `pad=0.3` | 112 | | Round | `round` | `pad=0.3,rounding_size=None` | 113 | | Round4 | `round4` | `pad=0.3,rounding_size=None` | 114 | | Roundtooth | `roundtooth` | `pad=0.3,tooth_size=None` | 115 | | Sawtooth | `sawtooth` | `pad=0.3,tooth_size=None` | 116 | | Square | `square` | `pad=0.3` | 117 | 118 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/fancybox_demo2.py) 119 | 120 | ![](http://matplotlib.org/_images/fancybox_demo22.png) 121 | 122 | 注意,属性参数可以在样式名称中用逗号分隔(在初始化文本实例时,此形式可以用作`bbox`参数的`boxstyle`的值)。 123 | 124 | ```py 125 | bb.set_boxstyle("rarrow,pad=0.6") 126 | ``` 127 | 128 | ### 使用箭头来标注 129 | 130 | 131 | `pyplot`模块(或`Axes`类的`annotate`方法)中的`annotate()`函数用于绘制连接图上两点的箭头。 132 | 133 | ```py 134 | ax.annotate("Annotation", 135 | xy=(x1, y1), xycoords='data', 136 | xytext=(x2, y2), textcoords='offset points', 137 | ) 138 | ``` 139 | 140 | 这会使用`textcoords`中提供的,`xytext`处的文本标注提供坐标(`xycoords`)中的`xy`处的点。 通常,数据坐标中规定了标注点,偏移点中规定了标注文本。 请参阅`annotate()`了解可用的坐标系。 141 | 142 | 连接两个点(`xy`和`xytext`)的箭头可以通过指定`arrowprops`参数可选地绘制。 为了仅绘制箭头,请使用空字符串作为第一个参数。 143 | 144 | ```py 145 | ax.annotate("", 146 | xy=(0.2, 0.2), xycoords='data', 147 | xytext=(0.8, 0.8), textcoords='data', 148 | arrowprops=dict(arrowstyle="->", 149 | connectionstyle="arc3"), 150 | ) 151 | ``` 152 | 153 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_simple01.py) 154 | 155 | ![](http://matplotlib.org/_images/annotate_simple01.png) 156 | 157 | 箭头的绘制需要几个步骤。 158 | 159 | + 创建两个点之间的连接路径。 这由`connectionstyle`键值控制。 160 | + 如果提供了补丁对象(`patchA`和`patchB`),则会剪切路径以避开该补丁。 161 | + 路径进一步由提供的像素总量来缩小(`shirnkA`&`shrinkB`) 162 | + 路径转换为箭头补丁,由`arrowstyle`键值控制。 163 | 164 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_explain.py) 165 | 166 | ![](http://matplotlib.org/_images/annotate_explain.png) 167 | 168 | 两个点之间的连接路径的创建由`connectionstyle `键控制,并且可用以下样式。 169 | 170 | | 名称 | 属性 | 171 | | --- | --- | 172 | | angle | `angleA=90,angleB=0,rad=0.0` | 173 | | angle3 | `angleA=90,angleB=0` | 174 | | arc | `angleA=0,angleB=0,armA=None,armB=None,rad=0.0` | 175 | | arc3 | `rad=0.0` | 176 | | bar | `armA=0.0,armB=0.0,fraction=0.3,angle=None` | 177 | 178 | 注意,`angle3`和`arc3`中的`3`意味着所得到的路径是二次样条段(三个控制点)。 如下面将讨论的,当连接路径是二次样条时,可以使用一些箭头样式选项。 179 | 180 | 每个连接样式的行为在下面的示例中(有限地)演示。 (警告:条形样式的行为当前未定义好,将来可能会更改)。 181 | 182 | [源代码](http://matplotlib.org/users/plotting/examples/connectionstyle_demo.py) 183 | 184 | ![](http://matplotlib.org/_images/connectionstyle_demo.png) 185 | 186 | 然后根据给定的箭头样式将连接路径(在剪切和收缩之后)变换为箭头补丁。 187 | 188 | | 名称 | 属性 | 189 | | --- | --- | 190 | | - | `None` | 191 | | -> | `head_length=0.4,head_width=0.2` | 192 | | -[ | `widthB=1.0,lengthB=0.2,angleB=None` | 193 | | |-| | `widthA=1.0,widthB=1.0` | 194 | | -|> | `head_length=0.4,head_width=0.2` | 195 | | <- | `head_length=0.4,head_width=0.2` | 196 | | <-> | `head_length=0.4,head_width=0.2` | 197 | | <|- | `head_length=0.4,head_width=0.2` | 198 | | <|-|> | `head_length=0.4,head_width=0.2` | 199 | | fancy | `head_length=0.4,head_width=0.4,tail_width=0.4` | 200 | | simple | `head_length=0.5,head_width=0.5,tail_width=0.2` | 201 | | wedge | `tail_width=0.3,shrink_factor=0.5` | 202 | 203 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/fancyarrow_demo.py) 204 | 205 | ![](http://matplotlib.org/_images/fancyarrow_demo2.png) 206 | 207 | 一些箭头仅适用于生成二次样条线段的连接样式。 他们是`fancy`,`simple`,`wedge`。 对于这些箭头样式,必须使用`angle3`或`arc3`连接样式。 208 | 209 | 如果提供了标注字符串,则`patchA`默认设置为文本的`bbox`补丁。 210 | 211 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_simple02.py) 212 | 213 | ![](http://matplotlib.org/_images/annotate_simple02.png) 214 | 215 | 与`text`命令一样,可以使用`bbox`参数来绘制文本周围的框。 216 | 217 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_simple03.py) 218 | 219 | ![](http://matplotlib.org/_images/annotate_simple03.png) 220 | 221 | 默认情况下,起点设置为文本范围的中心。 可以使用`relpos`键值进行调整。 这些值根据文本的范围进行归一化。 例如,`(0,0)`表示左下角,`(1,1)`表示右上角。 222 | 223 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_simple04.py) 224 | 225 | ![](http://matplotlib.org/_images/annotate_simple04.png) 226 | 227 | ### 将艺术家放置在轴域的锚定位置 228 | 229 | 有一类艺术家可以放置在轴域的锚定位置。 一个常见的例子是图例。 这种类型的艺术家可以使用`OffsetBox`类创建。 `mpl_toolkits.axes_grid.anchored_artists`中有几个预定义类。 230 | 231 | ```py 232 | from mpl_toolkits.axes_grid.anchored_artists import AnchoredText 233 | at = AnchoredText("Figure 1a", 234 | prop=dict(size=8), frameon=True, 235 | loc=2, 236 | ) 237 | at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") 238 | ax.add_artist(at) 239 | ``` 240 | 241 | [源代码](http://matplotlib.org/users/plotting/examples/anchored_box01.py) 242 | 243 | ![](http://matplotlib.org/_images/anchored_box01.png) 244 | 245 | `loc`关键字与`legend`命令中含义相同。 246 | 247 | 一个简单的应用是当艺术家(或艺术家的集合)的像素大小在创建时已知。 例如,如果要绘制一个固定大小为 20 像素 ×20 像素(半径为 10 像素)的圆,则可以使用`AnchoredDrawingArea`。 实例使用绘图区域的大小创建(以像素为单位)。 用户可以在绘图区任意添加艺术家。 注意,添加到绘图区域的艺术家的范围与绘制区域本身的位置无关,只和初始大小有关。 248 | 249 | ```py 250 | from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea 251 | 252 | ada = AnchoredDrawingArea(20, 20, 0, 0, 253 | loc=1, pad=0., frameon=False) 254 | p1 = Circle((10, 10), 10) 255 | ada.drawing_area.add_artist(p1) 256 | p2 = Circle((30, 10), 5, fc="r") 257 | ada.drawing_area.add_artist(p2) 258 | ``` 259 | 260 | 添加到绘图区域的艺术家不应该具有变换集(它们将被重写),并且那些艺术家的尺寸被解释为像素坐标,即,上述示例中的圆的半径分别是 10 像素和 5 像素。 261 | 262 | [源代码](http://matplotlib.org/users/plotting/examples/anchored_box02.py) 263 | 264 | ![](http://matplotlib.org/_images/anchored_box02.png) 265 | 266 | 有时,你想让你的艺术家按数据坐标(或其他坐标,而不是画布像素)缩放。 你可以使用`AnchoredAuxTransformBox`类。 这类似于`AnchoredDrawingArea`,除了艺术家的范围在绘制时由指定的变换确定。 267 | 268 | ```py 269 | from mpl_toolkits.axes_grid.anchored_artists import AnchoredAuxTransformBox 270 | 271 | box = AnchoredAuxTransformBox(ax.transData, loc=2) 272 | el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates! 273 | box.drawing_area.add_artist(el) 274 | ``` 275 | 276 | 上述示例中的椭圆具有在数据坐标中对应于 0.1 和 0.4 的宽度和高度,并且当轴域的视图限制改变时将自动缩放。 277 | 278 | [源代码](http://matplotlib.org/users/plotting/examples/anchored_box03.py) 279 | 280 | ![](http://matplotlib.org/_images/anchored_box03.png) 281 | 282 | 如图例所示,可以设置`bbox_to_anchor`参数。 使用`HPacker`和`VPacker`,你可以像图例中一样排列艺术家(事实上,这是图例的创建方式)。 283 | 284 | [源代码](http://matplotlib.org/users/plotting/examples/anchored_box04.py) 285 | 286 | ![](http://matplotlib.org/_images/anchored_box04.png) 287 | 288 | 请注意,与图例不同,默认情况下,`bbox_transform`设置为`IdentityTransform`。 289 | 290 | ### 使用复杂坐标来标注 291 | 292 | matplotlib 中的标注支持[标注文本](http://matplotlib.org/users/annotations_intro.html#annotations-tutorial)中描述的几种类型的坐标。 对于想要更多控制的高级用户,它支持几个其他选项。 293 | 294 | 1. `Transform`实例,例如: 295 | 296 | ```py 297 | ax.annotate("Test", xy=(0.5, 0.5), xycoords=ax.transAxes) 298 | ``` 299 | 300 | 相当于: 301 | 302 | ```py 303 | ax.annotate("Test", xy=(0.5, 0.5), xycoords="axes fraction") 304 | ``` 305 | 306 | 使用它,你可以在其他轴域内标注一个点: 307 | 308 | ```py 309 | ax1, ax2 = subplot(121), subplot(122) 310 | ax2.annotate("Test", xy=(0.5, 0.5), xycoords=ax1.transData, 311 | xytext=(0.5, 0.5), textcoords=ax2.transData, 312 | arrowprops=dict(arrowstyle="->")) 313 | ``` 314 | 315 | 2. `Artist`实例。`xy`值(或`xytext`)被解释为艺术家的`bbox`(`get_window_extent`的返回值)的小数坐标。 316 | 317 | ```py 318 | an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data", 319 | va="center", ha="center", 320 | bbox=dict(boxstyle="round", fc="w")) 321 | an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1, # (1,0.5) of the an1's bbox 322 | xytext=(30,0), textcoords="offset points", 323 | va="center", ha="left", 324 | bbox=dict(boxstyle="round", fc="w"), 325 | arrowprops=dict(arrowstyle="->")) 326 | ``` 327 | 328 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_simple_coord01.py) 329 | 330 | ![](http://matplotlib.org/_images/annotate_simple_coord01.png) 331 | 332 | 请注意,你的责任是在绘制`an2`之前确定坐标艺术家(上例中的`an1`)的范围。 在大多数情况下,这意味着`an2`需要晚于`an1`。 333 | 334 | 3. 一个返回`BboxBase`或`Transform`的实例的可调用对象。 如果返回一个变换,它与 1 相同,如果返回`bbox`,它与 2 相同。可调用对象应该接受`renderer`实例的单个参数。 例如,以下两个命令产生相同的结果: 335 | 336 | ```py 337 | an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1, 338 | xytext=(30,0), textcoords="offset points") 339 | an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1.get_window_extent, 340 | xytext=(30,0), textcoords="offset points") 341 | ``` 342 | 343 | 4. 指定二元坐标的元组。 第一项用于`x`坐标,第二项用于`y`坐标。 例如, 344 | 345 | ```py 346 | annotate("Test", xy=(0.5, 1), xycoords=("data", "axes fraction")) 347 | ``` 348 | 349 | 0.5 的单位是数据坐标,1 的单位是归一化轴域坐标。 你可以像使用元组一样使用艺术家或变换。 例如, 350 | 351 | ```py 352 | import matplotlib.pyplot as plt 353 | 354 | plt.figure(figsize=(3,2)) 355 | ax=plt.axes([0.1, 0.1, 0.8, 0.7]) 356 | an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data", 357 | va="center", ha="center", 358 | bbox=dict(boxstyle="round", fc="w")) 359 | 360 | an2 = ax.annotate("Test 2", xy=(0.5, 1.), xycoords=an1, 361 | xytext=(0.5,1.1), textcoords=(an1, "axes fraction"), 362 | va="bottom", ha="center", 363 | bbox=dict(boxstyle="round", fc="w"), 364 | arrowprops=dict(arrowstyle="->")) 365 | plt.show() 366 | ``` 367 | 368 | [源代码](http://matplotlib.org/users/plotting/examples/annotate_simple_coord02.py) 369 | 370 | ![](http://matplotlib.org/_images/annotate_simple_coord02.png) 371 | 372 | 5. 有时,您希望您的注释带有一些“偏移点”,不是距离注释点,而是距离某些其他点。 `OffsetFrom`是这种情况下的辅助类。 373 | 374 | ```py 375 | import matplotlib.pyplot as plt 376 | 377 | plt.figure(figsize=(3,2)) 378 | ax=plt.axes([0.1, 0.1, 0.8, 0.7]) 379 | an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data", 380 | va="center", ha="center", 381 | bbox=dict(boxstyle="round", fc="w")) 382 | 383 | from matplotlib.text import OffsetFrom 384 | offset_from = OffsetFrom(an1, (0.5, 0)) 385 | an2 = ax.annotate("Test 2", xy=(0.1, 0.1), xycoords="data", 386 | xytext=(0, -10), textcoords=offset_from, 387 | # xytext is offset points from "xy=(0.5, 0), xycoords=an1" 388 | va="top", ha="center", 389 | bbox=dict(boxstyle="round", fc="w"), 390 | arrowprops=dict(arrowstyle="->")) 391 | plt.show() 392 | ``` 393 | 394 | ![](http://matplotlib.org/_images/annotate_simple_coord03.png) 395 | 396 | 你可以参考这个链接:[`pylab_examples example code: annotation_demo3.py.`](http://matplotlib.org/examples/pylab_examples/annotation_demo3.html#pylab-examples-annotation-demo3)。 397 | 398 | ### 使用`ConnectorPatch` 399 | 400 | `ConnectorPatch`类似于没有文本的标注。 虽然在大多数情况下建议使用标注函数,但是当您想在不同的轴上连接点时,`ConnectorPatch`很有用。 401 | 402 | 403 | ```py 404 | from matplotlib.patches import ConnectionPatch 405 | xy = (0.2, 0.2) 406 | con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data", 407 | axesA=ax1, axesB=ax2) 408 | ax2.add_artist(con) 409 | ``` 410 | 411 | 上述代码连接了`ax1`中数据坐标的`xy`点,与`ax2`中数据坐标的`xy`点。这是个简单的例子。 412 | 413 | [源代码](http://matplotlib.org/users/plotting/examples/connect_simple01.py) 414 | 415 | ![](http://matplotlib.org/_images/connect_simple01.png) 416 | 417 | 虽然`ConnectorPatch`实例可以添加到任何轴,但您可能需要将其添加到绘图顺序中最新的轴,以防止与其他轴重叠。 418 | 419 | ## 高级话题 420 | 421 | ### 轴域之间的缩放效果 422 | 423 | `mpl_toolkits.axes_grid.inset_locator`定义了一些补丁类,用于互连两个轴域。 理解代码需要一些 mpl 转换如何工作的知识。 但是,利用它的方式很直接。 424 | 425 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/axes_zoom_effect.py) 426 | 427 | ![](http://matplotlib.org/_images/axes_zoom_effect1.png) 428 | 429 | ### 定义自定义盒样式 430 | 431 | 你可以使用自定义盒样式,`boxstyle`的值可以为如下形式的可调用对象: 432 | 433 | ```py 434 | def __call__(self, x0, y0, width, height, mutation_size, 435 | aspect_ratio=1.): 436 | """ 437 | Given the location and size of the box, return the path of 438 | the box around it. 439 | 440 | - *x0*, *y0*, *width*, *height* : location and size of the box 441 | - *mutation_size* : a reference scale for the mutation. 442 | - *aspect_ratio* : aspect-ratio for the mutation. 443 | """ 444 | path = ... 445 | return path 446 | ``` 447 | 448 | 这里是个复杂的例子: 449 | 450 | [源代码](http://matplotlib.org/users/plotting/examples/custom_boxstyle01.py) 451 | 452 | ![](http://matplotlib.org/_images/custom_boxstyle01.png) 453 | 454 | 但是,推荐你从`matplotlib.patches.BoxStyle._Base`派生,像这样: 455 | 456 | ```py 457 | from matplotlib.path import Path 458 | from matplotlib.patches import BoxStyle 459 | import matplotlib.pyplot as plt 460 | 461 | # we may derive from matplotlib.patches.BoxStyle._Base class. 462 | # You need to override transmute method in this case. 463 | 464 | class MyStyle(BoxStyle._Base): 465 | """ 466 | A simple box. 467 | """ 468 | 469 | def __init__(self, pad=0.3): 470 | """ 471 | The arguments need to be floating numbers and need to have 472 | default values. 473 | 474 | *pad* 475 | amount of padding 476 | """ 477 | 478 | self.pad = pad 479 | super(MyStyle, self).__init__() 480 | 481 | def transmute(self, x0, y0, width, height, mutation_size): 482 | """ 483 | Given the location and size of the box, return the path of 484 | the box around it. 485 | 486 | - *x0*, *y0*, *width*, *height* : location and size of the box 487 | - *mutation_size* : a reference scale for the mutation. 488 | 489 | Often, the *mutation_size* is the font size of the text. 490 | You don't need to worry about the rotation as it is 491 | automatically taken care of. 492 | """ 493 | 494 | # padding 495 | pad = mutation_size * self.pad 496 | 497 | # width and height with padding added. 498 | width, height = width + 2.*pad, \ 499 | height + 2.*pad, 500 | 501 | # boundary of the padded box 502 | x0, y0 = x0-pad, y0-pad, 503 | x1, y1 = x0+width, y0 + height 504 | 505 | cp = [(x0, y0), 506 | (x1, y0), (x1, y1), (x0, y1), 507 | (x0-pad, (y0+y1)/2.), (x0, y0), 508 | (x0, y0)] 509 | 510 | com = [Path.MOVETO, 511 | Path.LINETO, Path.LINETO, Path.LINETO, 512 | Path.LINETO, Path.LINETO, 513 | Path.CLOSEPOLY] 514 | 515 | path = Path(cp, com) 516 | 517 | return path 518 | 519 | 520 | # register the custom style 521 | BoxStyle._style_list["angled"] = MyStyle 522 | 523 | plt.figure(1, figsize=(3,3)) 524 | ax = plt.subplot(111) 525 | ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center", rotation=30, 526 | bbox=dict(boxstyle="angled,pad=0.5", alpha=0.2)) 527 | 528 | del BoxStyle._style_list["angled"] 529 | 530 | plt.show() 531 | ``` 532 | 533 | [源代码](http://matplotlib.org/users/plotting/examples/custom_boxstyle02.py) 534 | 535 | ![](http://matplotlib.org/_images/custom_boxstyle02.png) 536 | 537 | 与之类似,您可以定义一个自定义的`ConnectionStyle`和一个自定义的`ArrowStyle`。 请参阅`lib/matplotlib/patches.py`的源代码,并查看每个样式类是如何定义的。 538 | -------------------------------------------------------------------------------- /4.6.md: -------------------------------------------------------------------------------- 1 | # 编写数学表达式 2 | 3 | > 原文:[Writing mathematical expressions](http://matplotlib.org/users/mathtext.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 你可以在任何 matplotlib 文本字符串中使用子 TeX 标记,将它放在一对美元符号(`$`)内。 10 | 11 | 注意,你不需要安装 TeX,因为 matplotlib 提供了自己的 TeX 表达式解析器,布局引擎和字体。 布局引擎是 Donald Knuth 的 TeX 中的布局算法的一种相当直接的适配版,所以质量是相当不错的(matplotlib 还为那些想要调用 TeX 生成文本的人提供一个`usetex`选项(参见[使用 LaTeX 渲染文本](http://matplotlib.org/users/usetex.html#usetex-tutorial) )。 12 | 13 | 任何文本元素都可以使用数学文本。 你应该使用原始字符串(在引号前面加一个`'r'`),并用美元符号(`$`)包围数学文本,如 TeX。 常规文本和数学文本可以在同一个字符串内交错。 Mathtext 可以使用 Computer Modern 字体(来自 (La)TeX),STIX 字体(为与 Times 混合使用而设计)或你提供的 Unicode 字体。 可以使用自定义变量`mathtext.fontset`选择 mathtext 字体(请参阅[自定义 matplotlib](http://matplotlib.org/users/customizing.html#customizing-matplotlib)) 14 | 15 | > 注意 16 | 17 | > 在Python的 『narrow』 构建中,如果使用 STIX 字体,你还应该将`ps.fonttype`和`pdf.fonttype`设置为 3(默认值),而不是 42。否则一些字符将不可见。 18 | 19 | 下面是个简单的例子: 20 | 21 | ```py 22 | # plain text 23 | plt.title('alpha > beta') 24 | ``` 25 | 26 | 生成`alpha > beta`。 27 | 28 | 但是这个: 29 | 30 | ```py 31 | # math text 32 | plt.title(r'$\alpha > \beta$') 33 | ``` 34 | 35 | 生成 ![](http://matplotlib.org/_images/mathmpl/math-3ba37e0517.png)。 36 | 37 | > 注意 38 | 39 | > Mathtext 应该放在一对美元符号(`$`)之间。 为了易于显示货币值,例如`$ 100.00`,如果整个字符串中存在单个美元符号,则它将被逐字显示为美元符号。 这是常规 TeX 的一个小改变,其中非数学文本中的美元符号必须被转义(`'$'`)。 40 | 41 | > 注意 42 | 43 | > 虽然一对美元符号(`$`)内的语法是 TeX 风格的,但是外面的文本不是。 特别是,字符: 44 | 45 | > ``` 46 | > # $ % & ~ _ ^ \ { } \( \) \[ \] 47 | > ``` 48 | 49 | > 在 TeX 中的数学模式之外有特殊的意义。 因此,根据`rcParam text.usetex`标志这些字符的表现有所不同。 更多信息请参阅[`usetex`教程](http://matplotlib.org/users/usetex.html#usetex-tutorial)。 50 | 51 | ## 下标和上标 52 | 53 | 为了制作下标和上标,使用`_`或者`^`符号: 54 | 55 | ```py 56 | r'$\alpha_i > \beta_i$' 57 | ``` 58 | 59 | ![](http://matplotlib.org/_images/mathmpl/math-e2db32b4d0.png) 60 | 61 | 一些符号会自动将它们的下标或上标放在操作符的底部或顶部,例如,为了编写 0 到无穷的 ![](http://matplotlib.org/_images/mathmpl/math-ccea9f4e30.png) 的和,你可以: 62 | 63 | ```py 64 | r'$\sum_{i=0}^\infty x_i$' 65 | ``` 66 | 67 | ![](http://matplotlib.org/_images/mathmpl/math-a3ca6be911.png) 68 | 69 | ## 分数、二项式和堆叠数 70 | 71 | 可以使用`\frac{}{}`,`\binomial{}{}`和`\stackrel{}{}`命令分别创建分数,二项式和堆叠数字: 72 | 73 | ```py 74 | r'$\frac{3}{4} \binom{3}{4} \stackrel{3}{4}$' 75 | ``` 76 | 77 | 产生 78 | 79 | ![](http://matplotlib.org/_images/mathmpl/math-3025afbc71.png) 80 | 81 | 分数可以任意嵌套: 82 | 83 | ```py 84 | r'$\frac{5 - \frac{1}{x}}{4}$' 85 | ``` 86 | 87 | 产生 88 | 89 | ![](http://matplotlib.org/_images/mathmpl/math-2e885fe67f.png) 90 | 91 | 请注意,在分数周围放置圆括号和花括号需要特别注意。 这种明显的方式会产生太小的括号: 92 | 93 | ```py 94 | r'$(\frac{5 - \frac{1}{x}}{4})$' 95 | ``` 96 | 97 | ![](http://matplotlib.org/_images/mathmpl/math-07b17ba8f6.png) 98 | 99 | 解决方案是在括号前面加上`\left`和`\right`以通知解析器这些括号包含整个对象: 100 | 101 | ```py 102 | r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$' 103 | ``` 104 | 105 | ![](http://matplotlib.org/_images/mathmpl/math-9d267a8c3c.png) 106 | 107 | ## 根式 108 | 109 | 根式可以有`\sqrt[]{}`产生,例如: 110 | 111 | ```py 112 | r'$\sqrt{2}$' 113 | ``` 114 | 115 | ![](http://matplotlib.org/_images/mathmpl/math-f151e9b6c6.png) 116 | 117 | 方括号内可以(可选地)设置任何底数。 请注意,底数必须是一个简单的表达式,并且不能包含布局命令,如分数或上下标: 118 | 119 | ```py 120 | r'$\sqrt[3]{x}$' 121 | ``` 122 | 123 | ![](http://matplotlib.org/_images/mathmpl/math-6b6cc30aef.png) 124 | 125 | ## 字体 126 | 127 | 用于数学符号的默认字体是斜体。 128 | 129 | > 注意 130 | 131 | > 此默认值可以使用`mathtext.default` `rcParam`更改。 这是非常有用的,例如,通过将其设置为`regular`,使用与常规非数学文本相同的字体作为数学文本。 132 | 133 | 为了修改字体,例如,以罗马字体编写`sin`,使用字体命令来闭合文本: 134 | 135 | ```py 136 | r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$' 137 | ``` 138 | 139 | ![](http://matplotlib.org/_images/mathmpl/math-c8056d47b3.png) 140 | 141 | 142 | 这里`s`和`t`是斜体(默认)的变量,`sin`是罗马字体,振幅`A`是书法字体。 注意在上面的例子中,`A`和`sin`之间的间距被挤压。 你可以使用间距命令在它们之间添加一些空格: 143 | 144 | ``` 145 | s(t) = \mathcal{A}\/\sin(2 \omega t) 146 | ``` 147 | 148 | ![](http://matplotlib.org/_images/mathmpl/math-44f45b7160.png) 149 | 150 | 所有字体的可用选项为: 151 | 152 | | 命令 | 结果 | 153 | | --- | --- | 154 | | `\mathrm{Roman}` | ![](http://matplotlib.org/_images/mathmpl/math-89f87a2f0c.png) | 155 | | `\mathit{Italic}` | ![](http://matplotlib.org/_images/mathmpl/math-968de0e26b.png) | 156 | | `\mathtt{Typewriter}` | ![](http://matplotlib.org/_images/mathmpl/math-ca3f612baa.png) | 157 | | `\mathcal{CALLIGRAPHY}` | ![](http://matplotlib.org/_images/mathmpl/math-1f62587cf2.png) | 158 | 159 | 使用 STIX 字体时,你也可以选择: 160 | 161 | | 命令 | 结果 | 162 | | --- | --- | 163 | | `\mathbb{blackboard}` | ![](http://matplotlib.org/_images/mathmpl/math-a12676f03f.png) | 164 | | `\mathrm{\mathbb{blackboard}}` | ![](http://matplotlib.org/_images/mathmpl/math-014e74dc81.png) | 165 | | `\mathfrak{Fraktur}` | ![](http://matplotlib.org/_images/mathmpl/math-4f55ade322.png) | 166 | | `\mathsf{sansserif}` | ![](http://matplotlib.org/_images/mathmpl/math-e9444fe0c8.png) | 167 | | `\mathrm{\mathsf{sansserif}}` | ![](http://matplotlib.org/_images/mathmpl/math-c3a13bbc63.png) | 168 | | `\mathcircled{circled}` | ![](http://matplotlib.org/_images/mathmpl/math-e82daa3fb7.png) | 169 | 170 | 还有三个全局『字体集』可供选择,它们使用`matplotlibrc`中的`mathtext.fontset`参数进行选择。 171 | 172 | `cm`: Computer Modern (TeX) 173 | 174 | ![](http://matplotlib.org/_images/cm_fontset.png) 175 | 176 | `stix`: STIX (为和 Times 混合使用而设计) 177 | 178 | ![](http://matplotlib.org/_images/stix_fontset.png) 179 | 180 | `stixsans`: STIX sans-serif 181 | 182 | ![](http://matplotlib.org/_images/stixsans_fontset.png) 183 | 184 | 此外,你可以使用`\mathdefault{...}`或其别名`\mathregular{...}`来使用用于 mathtext 之外的常规文本的字体。 这种方法有一些限制,最明显的是,可以使用很少的符号,但可用于将数学表达式与图中的其他文本混合。 185 | 186 | ## 自定义字体 187 | 188 | mathtext 还提供了一种对数学公式使用自定义字体的方法。 这种方法使用起来相当棘手,应该看做为有耐心的用户准备的试验特性。 通过将`rcParam mathtext.fontset`设置为`custom`,你可以设置以下参数,这些参数控制用于特定数学字符集的字体文件。 189 | 190 | | 参数 | 相当于 | 191 | | --- | --- | 192 | | `mathtext.it` | `\mathit{}` 默认斜体 | 193 | | `mathtext.rm` | `\mathrm{}` 罗马字体(upright) | 194 | | `mathtext.tt` | `\mathtt{}` 打字机(monospace) | 195 | | `mathtext.bf` | `\mathbf{}` 粗体 | 196 | | `mathtext.cal` | `\mathcal{}` 书法 | 197 | | `mathtext.sf` | `\mathsf{}` sans-serif | 198 | 199 | 每个参数应该设置为`fontconfig`字体描述符(在尚未编写的字体章节中定义)。 200 | 201 | 所使用的字体应该具有 Unicode 映射,以便找到任何非拉丁字符,例如希腊语。 如果要使用未包含在自定义字体中的数学符号,可以将`rcParam mathtext.fallback_to_cm`设置为`True`,这将导致自定义字体中找不到特定字符时,数学文本系统使用默认的 Computer Modern 字体中的字符。 202 | 203 | 请注意,Unicode 中规定的数学字形随时间而演进,许多字体的字形对于 mathtext 可能不在正确位置。 204 | 205 | ## 重音符号 206 | 207 | 重音命令可以位于任何符号之前,在其上添加重音。 他们中的一些些拥有较长和较短的形式。 208 | 209 | | 命令 | 结果 | 210 | | --- | --- | 211 | | `\acute a` 或 `\'a` | ![](http://matplotlib.org/_images/mathmpl/math-fac074d098.png) | 212 | | `\bar a` | ![](http://matplotlib.org/_images/mathmpl/math-b7c546c13f.png) | 213 | | `\breve a` | ![](http://matplotlib.org/_images/mathmpl/math-88814f8d66.png) | 214 | | `\ddot a` 或 `\"a` | ![](http://matplotlib.org/_images/mathmpl/math-adb99bedc4.png) | 215 | | `\dot a` 或 `\.a` | ![](http://matplotlib.org/_images/mathmpl/math-b5496f6786.png) | 216 | | `\grave a` 或 `\`a` | ![](http://matplotlib.org/_images/mathmpl/math-54cbc28bce.png) | 217 | | `\hat a` 或 `\^a` | ![](http://matplotlib.org/_images/mathmpl/math-16da2c10a1.png) | 218 | | `\tilde a` 或 `\~a` | ![](http://matplotlib.org/_images/mathmpl/math-3a8b2e99d6.png) | 219 | | `\vec a` | ![](http://matplotlib.org/_images/mathmpl/math-be2ea18bef.png) | 220 | | `\overline{abc}` | ![](http://matplotlib.org/_images/mathmpl/math-75e95f3f2b.png) | 221 | 222 | 另外有两个特殊的重音符号,可以自动调整为符号的宽度: 223 | 224 | | 命令 | 结果 | 225 | | --- | --- | 226 | | `\widehat{xyz}` | ![](http://matplotlib.org/_images/mathmpl/math-8e4b9eb82b.png) | 227 | | `\widetilde{xyz}` | ![](http://matplotlib.org/_images/mathmpl/math-bf67fbdaae.png) | 228 | 229 | 当把重音放在小写的`i`和`j`上时应该小心。 注意下面的`\imath`用来避免`i`上额外的点: 230 | 231 | ```py 232 | r"$\hat i\ \ \hat \imath$" 233 | ``` 234 | 235 | ![](http://matplotlib.org/_images/mathmpl/math-80117b16d3.png) 236 | 237 | ## 符号 238 | 239 | 你也可以使用更大量的 TeX 符号,比如`\infty`,`\leftarrow`,`\sum`,`\int`。 240 | 241 | 242 | | 小写希腊字母 | | | 243 | | --- | --- | --- | 244 | | ![](http://matplotlib.org/_images/mathmpl/math-5149852f08.png) `\alpha` | ![](http://matplotlib.org/_images/mathmpl/math-59ed813421.png) `\beta` | ![](http://matplotlib.org/_images/mathmpl/math-7d54d13fc9.png) `\chi` | ![](http://matplotlib.org/_images/mathmpl/math-e15357ad29.png) `\delta` | ![](http://matplotlib.org/_images/mathmpl/math-41188a0c1b.png) `\digamma` | 245 | | ![](http://matplotlib.org/_images/mathmpl/math-21b6ff3aa7.png) `\epsilon` | ![](http://matplotlib.org/_images/mathmpl/math-0fa258552e.png) `\eta` | ![](http://matplotlib.org/_images/mathmpl/math-ae65c1de79.png) `\gamma` | ![](http://matplotlib.org/_images/mathmpl/math-ff6a67483e.png) `\iota` | ![](http://matplotlib.org/_images/mathmpl/math-436efe52d1.png) `\kappa` | 246 | | ![](http://matplotlib.org/_images/mathmpl/math-3642ca147d.png) `\lambda` | ![](http://matplotlib.org/_images/mathmpl/math-3488de1d0a.png) `\mu` | ![](http://matplotlib.org/_images/mathmpl/math-79a0df421c.png) `\nu` | ![](http://matplotlib.org/_images/mathmpl/math-b555ccd28d.png) `\omega` | ![](http://matplotlib.org/_images/mathmpl/math-e22cc525ec.png) `\phi` | 247 | | ![](http://matplotlib.org/_images/mathmpl/math-2c7a9dac6d.png) `\pi` | ![](http://matplotlib.org/_images/mathmpl/math-3fc9142b1d.png) `\psi` | ![](http://matplotlib.org/_images/mathmpl/math-f2e3547a85.png) `\rho` | ![](http://matplotlib.org/_images/mathmpl/math-293c147d21.png) `\sigma` | ![](http://matplotlib.org/_images/mathmpl/math-f970af607c.png) `\tau` | 248 | | ![](http://matplotlib.org/_images/mathmpl/math-5dc8912759.png) `\theta` | ![](http://matplotlib.org/_images/mathmpl/math-ac7cfff3a1.png) `\upsilon` | ![](http://matplotlib.org/_images/mathmpl/math-a88976d8dd.png) `\varepsilon` | ![](http://matplotlib.org/_images/mathmpl/math-67a8f5ca79.png) `\varkappa` | ![](http://matplotlib.org/_images/mathmpl/math-a79325da6f.png) `\varphi` | 249 | | ![](http://matplotlib.org/_images/mathmpl/math-5e94f6d1ef.png) `\varpi` | ![](http://matplotlib.org/_images/mathmpl/math-d6c1d2bb14.png) `\varrho` | ![](http://matplotlib.org/_images/mathmpl/math-92fc1ff85f.png) `\varsigma` | ![](http://matplotlib.org/_images/mathmpl/math-d11bf19a50.png) `\vartheta` | ![](http://matplotlib.org/_images/mathmpl/math-1859062b14.png) `\xi` | 250 | | ![](http://matplotlib.org/_images/mathmpl/math-d51bb4d6d4.png) `\zeta` | 251 | 252 | | 大写希腊字母 | | | 253 | | --- | --- | --- | 254 | | ![](http://matplotlib.org/_images/mathmpl/math-e3168b0fff.png) `\Delta` | ![](http://matplotlib.org/_images/mathmpl/math-4eacc6ba71.png) `\Gamma` | ![](http://matplotlib.org/_images/mathmpl/math-a57791e0e2.png) `\Lambda` | ![](http://matplotlib.org/_images/mathmpl/math-28d3e90e31.png) `\Omega` | ![](http://matplotlib.org/_images/mathmpl/math-cebfe4186d.png) `\Phi` | ![](http://matplotlib.org/_images/mathmpl/math-3b938a5601.png) `\Pi` | 255 | | ![](http://matplotlib.org/_images/mathmpl/math-d44376b8c3.png) `\Psi` | ![](http://matplotlib.org/_images/mathmpl/math-076bf05243.png) `\Sigma` | ![](http://matplotlib.org/_images/mathmpl/math-98c28d2d1b.png) `\Theta` | ![](http://matplotlib.org/_images/mathmpl/math-43a44ec8e4.png) `\Upsilon` | ![](http://matplotlib.org/_images/mathmpl/math-376450e92a.png) `\Xi` | ![](http://matplotlib.org/_images/mathmpl/math-ab04245089.png) `\mho` | 256 | | ![](http://matplotlib.org/_images/mathmpl/math-9544659959.png) `\nabla` | 257 | 258 | | 希伯来文 | | | 259 | | --- | --- | --- | 260 | | ![](http://matplotlib.org/_images/mathmpl/math-d115134b0c.png) `\aleph` | ![](http://matplotlib.org/_images/mathmpl/math-b1d46891d0.png) `\beth` | ![](http://matplotlib.org/_images/mathmpl/math-ad0c7d5fd3.png) `\daleth` | ![](http://matplotlib.org/_images/mathmpl/math-4a68c72624.png) `\gimel` | 261 | 262 | | 分隔符 | | | 263 | | --- | --- | --- | 264 | | ![](http://matplotlib.org/_images/mathmpl/math-9d750cc7d9.png) `/` | ![](http://matplotlib.org/_images/mathmpl/math-1f9db75fdb.png) `[` | ![](http://matplotlib.org/_images/mathmpl/math-0c8ba18b43.png) `\Downarrow` | ![](http://matplotlib.org/_images/mathmpl/math-d00ab41d80.png) `\Uparrow` | ![](http://matplotlib.org/_images/mathmpl/math-2480720752.png) `\Vert` | ![](http://matplotlib.org/_images/mathmpl/math-b6a35dc0d4.png) `\backslash` | 265 | | ![](http://matplotlib.org/_images/mathmpl/math-56b7078922.png) `\downarrow` | ![](http://matplotlib.org/_images/mathmpl/math-46c392f788.png) `\langle` | ![](http://matplotlib.org/_images/mathmpl/math-6c35839641.png) `\lceil` | ![](http://matplotlib.org/_images/mathmpl/math-145ca7a5e7.png) `\lfloor` | ![](http://matplotlib.org/_images/mathmpl/math-554199c05b.png) `\llcorner` | ![](http://matplotlib.org/_images/mathmpl/math-057e1a984d.png) `\lrcorner` | 266 | | ![](http://matplotlib.org/_images/mathmpl/math-ef94320557.png) `\rangle` | ![](http://matplotlib.org/_images/mathmpl/math-cbd4824a55.png) `\rceil` | ![](http://matplotlib.org/_images/mathmpl/math-c8d83de344.png) `\rfloor` | ![](http://matplotlib.org/_images/mathmpl/math-de64de5819.png) `\ulcorner` | ![](http://matplotlib.org/_images/mathmpl/math-f1bfb0bbf7.png) `\uparrow` | ![](http://matplotlib.org/_images/mathmpl/math-4f8107394b.png) `\urcorner` | 267 | | ![](http://matplotlib.org/_images/mathmpl/math-e12e277d39.png) `\vert` | ![](http://matplotlib.org/_images/mathmpl/math-f81f19a962.png) `\{` | ![](http://matplotlib.org/_images/mathmpl/math-ee61bb7cf9.png) `\|` | ![](http://matplotlib.org/_images/mathmpl/math-19097cff83.png) `\}` | ![](http://matplotlib.org/_images/mathmpl/math-d35c7fd4db.png) `]` | ![](http://matplotlib.org/_images/mathmpl/math-dfa04fb947.png) `|` | 268 | 269 | | 大型符号 | | | 270 | | --- | --- | --- | 271 | | ![](http://matplotlib.org/_images/mathmpl/math-db9b9e0126.png) `\bigcap` | ![](http://matplotlib.org/_images/mathmpl/math-52ee117ecd.png) `\bigcup` | ![](http://matplotlib.org/_images/mathmpl/math-a31bc74ee2.png) `\bigodot` | ![](http://matplotlib.org/_images/mathmpl/math-011efae7a0.png) `\bigoplus` | ![](http://matplotlib.org/_images/mathmpl/math-e8cf7f5844.png) `\bigotimes` | 272 | | ![](http://matplotlib.org/_images/mathmpl/math-8f896d9410.png) `\biguplus` | ![](http://matplotlib.org/_images/mathmpl/math-1de8afe642.png) `\bigvee` | ![](http://matplotlib.org/_images/mathmpl/math-888740ee66.png) `\bigwedge` | ![](http://matplotlib.org/_images/mathmpl/math-1bb3130224.png) `\coprod` | ![](http://matplotlib.org/_images/mathmpl/math-1610e87ea8.png) `\int` | 273 | | ![](http://matplotlib.org/_images/mathmpl/math-ce75170225.png) `\oint` | ![](http://matplotlib.org/_images/mathmpl/math-e661b1289d.png) `\prod` | ![](http://matplotlib.org/_images/mathmpl/math-f6fb720d82.png) `\sum` | 274 | 275 | | 标准函数名称 | | | 276 | | --- | --- | --- | 277 | | ![](http://matplotlib.org/_images/mathmpl/math-a174a79fa7.png) `\Pr` | ![](http://matplotlib.org/_images/mathmpl/math-c7d2b9a8fd.png) `\arccos` | ![](http://matplotlib.org/_images/mathmpl/math-bab33d6e68.png) `\arcsin` | ![](http://matplotlib.org/_images/mathmpl/math-f8ee41a28a.png) `\arctan` | 278 | | ![](http://matplotlib.org/_images/mathmpl/math-510e2aecba.png) `\arg` | ![](http://matplotlib.org/_images/mathmpl/math-a539c63e58.png) `\cos` | ![](http://matplotlib.org/_images/mathmpl/math-46d99aa165.png) `\cosh` | ![](http://matplotlib.org/_images/mathmpl/math-06c793e494.png) `\cot` | 279 | | ![](http://matplotlib.org/_images/mathmpl/math-993151c5de.png) `\coth` | ![](http://matplotlib.org/_images/mathmpl/math-c72f36312c.png) `\csc` | ![](http://matplotlib.org/_images/mathmpl/math-efdcd0e7c3.png) `\deg` | ![](http://matplotlib.org/_images/mathmpl/math-a4f974e6ac.png) `\det` | 280 | | ![](http://matplotlib.org/_images/mathmpl/math-4ceaca4089.png) `\dim` | ![](http://matplotlib.org/_images/mathmpl/math-9b8a721035.png) `\exp` | ![](http://matplotlib.org/_images/mathmpl/math-705a921d5a.png) `\gcd` | ![](http://matplotlib.org/_images/mathmpl/math-ec200f4f3a.png) `\hom` | 281 | | ![](http://matplotlib.org/_images/mathmpl/math-d78d7b5c1b.png) `\inf` | ![](http://matplotlib.org/_images/mathmpl/math-9c3c23a23d.png) `\ker` | ![](http://matplotlib.org/_images/mathmpl/math-0c0d015405.png) `\lg` | ![](http://matplotlib.org/_images/mathmpl/math-441aa359eb.png) `\lim` | 282 | | ![](http://matplotlib.org/_images/mathmpl/math-2f010c89dd.png) `\liminf` | ![](http://matplotlib.org/_images/mathmpl/math-a9a0109ea9.png) `\limsup` | ![](http://matplotlib.org/_images/mathmpl/math-a5edc7016a.png) `\ln` | ![](http://matplotlib.org/_images/mathmpl/math-e5cdb1d314.png) `\log` | 283 | | ![](http://matplotlib.org/_images/mathmpl/math-fb64cdd50f.png) `\max` | ![](http://matplotlib.org/_images/mathmpl/math-bf7d25e347.png) `\min` | ![](http://matplotlib.org/_images/mathmpl/math-a0b5414d31.png) `\sec` | ![](http://matplotlib.org/_images/mathmpl/math-d8d19f17ef.png) `\sin` | 284 | | ![](http://matplotlib.org/_images/mathmpl/math-fce9663ad9.png) `\sinh` | ![](http://matplotlib.org/_images/mathmpl/math-358f2a2131.png) `\sup` | ![](http://matplotlib.org/_images/mathmpl/math-fb3512b848.png) `\tan` | ![](http://matplotlib.org/_images/mathmpl/math-8e6df07c24.png) `\tanh` | 285 | 286 | | 二元运算符和关系符号 | | | 287 | | --- | --- | --- | 288 | | ![](http://matplotlib.org/_images/mathmpl/math-f610b8e469.png) `\Bumpeq` | ![](http://matplotlib.org/_images/mathmpl/math-2a327a85e8.png) `\Cap` | ![](http://matplotlib.org/_images/mathmpl/math-0fbbe481d0.png) `\Cup` | 289 | | ![](http://matplotlib.org/_images/mathmpl/math-2303577dee.png) `\Doteq` | ![](http://matplotlib.org/_images/mathmpl/math-70e89758da.png) `\Join` | ![](http://matplotlib.org/_images/mathmpl/math-3d85215bfa.png) `\Subset` | 290 | | ![](http://matplotlib.org/_images/mathmpl/math-191c6ba7fa.png) `\Supset` | ![](http://matplotlib.org/_images/mathmpl/math-219444d8f5.png) `\Vdash` | ![](http://matplotlib.org/_images/mathmpl/math-7db176731c.png) `\Vvdash` | 291 | | ![](http://matplotlib.org/_images/mathmpl/math-c957a5ae9f.png) `\approx` | ![](http://matplotlib.org/_images/mathmpl/math-cf8f5e2275.png) `\approxeq` | ![](http://matplotlib.org/_images/mathmpl/math-4ea8b1e13e.png) `\ast` | 292 | | ![](http://matplotlib.org/_images/mathmpl/math-23c4970a1a.png) `\asymp` | ![](http://matplotlib.org/_images/mathmpl/math-ea0303ad72.png) `\backepsilon` | ![](http://matplotlib.org/_images/mathmpl/math-b1d77626bb.png) `\backsim` | 293 | | ![](http://matplotlib.org/_images/mathmpl/math-af3bc8ac21.png) `\backsimeq` | ![](http://matplotlib.org/_images/mathmpl/math-71771b9385.png) `\barwedge` | ![](http://matplotlib.org/_images/mathmpl/math-937e2c148d.png) `\because` | 294 | | ![](http://matplotlib.org/_images/mathmpl/math-51ae43b24b.png) `\between` | ![](http://matplotlib.org/_images/mathmpl/math-3b72c12de0.png) `\bigcirc` | ![](http://matplotlib.org/_images/mathmpl/math-e98739824f.png) `\bigtriangledown` | 295 | | ![](http://matplotlib.org/_images/mathmpl/math-52ddd6655e.png) `\bigtriangleup` | ![](http://matplotlib.org/_images/mathmpl/math-679967c920.png) `\blacktriangleleft` | ![](http://matplotlib.org/_images/mathmpl/math-2ff97d8581.png) `\blacktriangleright` | 296 | | ![](http://matplotlib.org/_images/mathmpl/math-d2bc160257.png) `\bot` | ![](http://matplotlib.org/_images/mathmpl/math-88c0703f35.png) `\bowtie` | ![](http://matplotlib.org/_images/mathmpl/math-0cc3cb6c41.png) `\boxdot` | 297 | | ![](http://matplotlib.org/_images/mathmpl/math-b5a379f4e8.png) `\boxminus` | ![](http://matplotlib.org/_images/mathmpl/math-3e25be9041.png) `\boxplus` | ![](http://matplotlib.org/_images/mathmpl/math-d3219d7443.png) `\boxtimes` | 298 | | ![](http://matplotlib.org/_images/mathmpl/math-ef7a046183.png) `\bullet` | ![](http://matplotlib.org/_images/mathmpl/math-c5baac4e57.png) `\bumpeq` | ![](http://matplotlib.org/_images/mathmpl/math-f0c7f8f01c.png) `\cap` | 299 | | ![](http://matplotlib.org/_images/mathmpl/math-5a90bc5099.png) `\cdot` | ![](http://matplotlib.org/_images/mathmpl/math-f9b0df773f.png) `\circ` | ![](http://matplotlib.org/_images/mathmpl/math-5af298e692.png) `\circeq` | 300 | | ![](http://matplotlib.org/_images/mathmpl/math-e4d9d4c64b.png) `\coloneq` | ![](http://matplotlib.org/_images/mathmpl/math-b43c061111.png) `\cong` | ![](http://matplotlib.org/_images/mathmpl/math-20b287ac85.png) `\cup` | 301 | | ![](http://matplotlib.org/_images/mathmpl/math-c0df1e9b19.png) `\curlyeqprec` | ![](http://matplotlib.org/_images/mathmpl/math-995f666935.png) `\curlyeqsucc` | ![](http://matplotlib.org/_images/mathmpl/math-615de138a6.png) `\curlyvee` | 302 | | ![](http://matplotlib.org/_images/mathmpl/math-5af1fa6042.png) `\curlywedge` | ![](http://matplotlib.org/_images/mathmpl/math-9b12241d0c.png) `\dag` | ![](http://matplotlib.org/_images/mathmpl/math-9e1beabce9.png) `\dashv` | 303 | | ![](http://matplotlib.org/_images/mathmpl/math-f0fa40854a.png) `\ddag` | ![](http://matplotlib.org/_images/mathmpl/math-765d4eae57.png) `\diamond` | ![](http://matplotlib.org/_images/mathmpl/math-a1903b29fd.png) `\div` | 304 | | ![](http://matplotlib.org/_images/mathmpl/math-3df678db55.png) `\divideontimes` | ![](http://matplotlib.org/_images/mathmpl/math-a5b22dbdac.png) `\doteq` | ![](http://matplotlib.org/_images/mathmpl/math-ff23293ae5.png) `\doteqdot` | 305 | | ![](http://matplotlib.org/_images/mathmpl/math-397b5fc155.png) `\dotplus` | ![](http://matplotlib.org/_images/mathmpl/math-d5242ce585.png) `\doublebarwedge` | ![](http://matplotlib.org/_images/mathmpl/math-a4f1a69c76.png) `\eqcirc` | 306 | | ![](http://matplotlib.org/_images/mathmpl/math-17826fcd24.png) `\eqcolon` | ![](http://matplotlib.org/_images/mathmpl/math-c104febab3.png) `\eqsim` | ![](http://matplotlib.org/_images/mathmpl/math-45eaae26d2.png) `\eqslantgtr` | 307 | | ![](http://matplotlib.org/_images/mathmpl/math-c3fea548da.png) `\eqslantless` | ![](http://matplotlib.org/_images/mathmpl/math-cc1340c453.png) `\equiv` | ![](http://matplotlib.org/_images/mathmpl/math-7965c0c1af.png) `\fallingdotseq` | 308 | | ![](http://matplotlib.org/_images/mathmpl/math-a41c184ca6.png) `\frown` | ![](http://matplotlib.org/_images/mathmpl/math-0bf42a25bb.png) `\geq` | ![](http://matplotlib.org/_images/mathmpl/math-9b14251f65.png) `\geqq` | 309 | | ![](http://matplotlib.org/_images/mathmpl/math-1fca7a951f.png) `\geqslant` | ![](http://matplotlib.org/_images/mathmpl/math-f9990bc9cf.png) `\gg` | ![](http://matplotlib.org/_images/mathmpl/math-a3de1e5b51.png) `\ggg` | 310 | | ![](http://matplotlib.org/_images/mathmpl/math-04c47dcb6e.png) `\gnapprox` | ![](http://matplotlib.org/_images/mathmpl/math-a3f9f1f014.png) `\gneqq` | ![](http://matplotlib.org/_images/mathmpl/math-793d9cedd0.png) `\gnsim` | 311 | | ![](http://matplotlib.org/_images/mathmpl/math-207852189a.png) `\gtrapprox` | ![](http://matplotlib.org/_images/mathmpl/math-9336896bb3.png) `\gtrdot` | ![](http://matplotlib.org/_images/mathmpl/math-4cd21f8ba6.png) `\gtreqless` | 312 | | ![](http://matplotlib.org/_images/mathmpl/math-18a0084a2d.png) `\gtreqqless` | ![](http://matplotlib.org/_images/mathmpl/math-8e388594ad.png) `\gtrless` | ![](http://matplotlib.org/_images/mathmpl/math-9d5e427aeb.png) `\gtrsim` | 313 | | ![](http://matplotlib.org/_images/mathmpl/math-58e3fcf6fd.png) `\in` | ![](http://matplotlib.org/_images/mathmpl/math-0e049fe80b.png) `\intercal` | ![](http://matplotlib.org/_images/mathmpl/math-1a503a50f2.png) `\leftthreetimes` | 314 | | ![](http://matplotlib.org/_images/mathmpl/math-aca311c641.png) `\leq` | ![](http://matplotlib.org/_images/mathmpl/math-d87b34b699.png) `\leqq` | ![](http://matplotlib.org/_images/mathmpl/math-764751dad5.png) `\leqslant` | 315 | | ![](http://matplotlib.org/_images/mathmpl/math-b8571a3cc2.png) `\lessapprox` | ![](http://matplotlib.org/_images/mathmpl/math-6cb5c3c310.png) `\lessdot` | ![](http://matplotlib.org/_images/mathmpl/math-1632a38331.png) `\lesseqgtr` | 316 | | ![](http://matplotlib.org/_images/mathmpl/math-d367d088c6.png) `\lesseqqgtr` | ![](http://matplotlib.org/_images/mathmpl/math-268c486057.png) `\lessgtr` | ![](http://matplotlib.org/_images/mathmpl/math-b53ab799d1.png) `\lesssim` | 317 | | ![](http://matplotlib.org/_images/mathmpl/math-f5e02865f3.png) `\ll` | ![](http://matplotlib.org/_images/mathmpl/math-2303518311.png) `\lll` | ![](http://matplotlib.org/_images/mathmpl/math-c408639f33.png) `\lnapprox` | 318 | | ![](http://matplotlib.org/_images/mathmpl/math-38bf4cf10d.png) `\lneqq` | ![](http://matplotlib.org/_images/mathmpl/math-ad67ff4a6f.png) `\lnsim` | ![](http://matplotlib.org/_images/mathmpl/math-f557917efd.png) `\ltimes` | 319 | | ![](http://matplotlib.org/_images/mathmpl/math-96c9a8ca95.png) `\mid` | ![](http://matplotlib.org/_images/mathmpl/math-b5ae8c62a3.png) `\models` | ![](http://matplotlib.org/_images/mathmpl/math-608c4a02ea.png) `\mp` | 320 | | ![](http://matplotlib.org/_images/mathmpl/math-e0ca686f62.png) `\nVDash` | ![](http://matplotlib.org/_images/mathmpl/math-4d5d5f4ffb.png) `\nVdash` | ![](http://matplotlib.org/_images/mathmpl/math-8aa32761da.png) `\napprox` | 321 | | ![](http://matplotlib.org/_images/mathmpl/math-92306485fb.png) `\ncong` | ![](http://matplotlib.org/_images/mathmpl/math-6e6c5971ad.png) `\ne` | ![](http://matplotlib.org/_images/mathmpl/math-da1122f776.png) `\neq` | 322 | | ![](http://matplotlib.org/_images/mathmpl/math-da1122f776.png) `\neq` | ![](http://matplotlib.org/_images/mathmpl/math-989088989a.png) `\nequiv` | ![](http://matplotlib.org/_images/mathmpl/math-07c03ece9c.png) `\ngeq` | 323 | | ![](http://matplotlib.org/_images/mathmpl/math-c2c43a5762.png) `\ngtr` | ![](http://matplotlib.org/_images/mathmpl/math-7e90b124a8.png) `\ni` | ![](http://matplotlib.org/_images/mathmpl/math-1c2ed5670a.png) `\nleq` | 324 | | ![](http://matplotlib.org/_images/mathmpl/math-c9136df47e.png) `\nless` | ![](http://matplotlib.org/_images/mathmpl/math-4c5d76f523.png) `\nmid` | ![](http://matplotlib.org/_images/mathmpl/math-9afe2d20f8.png) `\notin` | 325 | | ![](http://matplotlib.org/_images/mathmpl/math-e63a2108d5.png) `\nparallel` | ![](http://matplotlib.org/_images/mathmpl/math-201b65e42c.png) `\nprec` | ![](http://matplotlib.org/_images/mathmpl/math-37454f1e25.png) `\nsim` | 326 | | ![](http://matplotlib.org/_images/mathmpl/math-b045970090.png) `\nsubset` | ![](http://matplotlib.org/_images/mathmpl/math-e2dcef116c.png) `\nsubseteq` | ![](http://matplotlib.org/_images/mathmpl/math-0dc1c96f16.png) `\nsucc` | 327 | | ![](http://matplotlib.org/_images/mathmpl/math-0d1363d575.png) `\nsupset` | ![](http://matplotlib.org/_images/mathmpl/math-8963eae853.png) `\nsupseteq` | ![](http://matplotlib.org/_images/mathmpl/math-2eaa265b46.png) `\ntriangleleft` | 328 | | ![](http://matplotlib.org/_images/mathmpl/math-343170b287.png) `\ntrianglelefteq` | ![](http://matplotlib.org/_images/mathmpl/math-813dcf0a93.png) `\ntriangleright` | ![](http://matplotlib.org/_images/mathmpl/math-df6899ad3e.png) `\ntrianglerighteq` | 329 | | ![](http://matplotlib.org/_images/mathmpl/math-a55f718abe.png) `\nvDash` | ![](http://matplotlib.org/_images/mathmpl/math-fefbb15af0.png) `\nvdash` | ![](http://matplotlib.org/_images/mathmpl/math-b8348856ea.png) `\odot` | 330 | | ![](http://matplotlib.org/_images/mathmpl/math-497b831b05.png) `\ominus` | ![](http://matplotlib.org/_images/mathmpl/math-cfcebc2ef8.png) `\oplus` | ![](http://matplotlib.org/_images/mathmpl/math-6fd5eead33.png) `\oslash` | 331 | | ![](http://matplotlib.org/_images/mathmpl/math-3d7ac4bb5c.png) `\otimes` | ![](http://matplotlib.org/_images/mathmpl/math-305e05a6ab.png) `\parallel` | ![](http://matplotlib.org/_images/mathmpl/math-86ea2beb93.png) `\perp` | 332 | | ![](http://matplotlib.org/_images/mathmpl/math-62d5e1ef75.png) `\pitchfork` | ![](http://matplotlib.org/_images/mathmpl/math-813255d42d.png) `\pm` | ![](http://matplotlib.org/_images/mathmpl/math-2a54002803.png) `\prec` | 333 | | ![](http://matplotlib.org/_images/mathmpl/math-6f127405a3.png) `\precapprox` | ![](http://matplotlib.org/_images/mathmpl/math-5686c5a93f.png) `\preccurlyeq` | ![](http://matplotlib.org/_images/mathmpl/math-c6975aea0e.png) `\preceq` | 334 | | ![](http://matplotlib.org/_images/mathmpl/math-53e4edd44d.png) `\precnapprox` | ![](http://matplotlib.org/_images/mathmpl/math-b7c281dd54.png) `\precnsim` | ![](http://matplotlib.org/_images/mathmpl/math-58f182e47e.png) `\precsim` | 335 | | ![](http://matplotlib.org/_images/mathmpl/math-4225d47da8.png) `\propto` | ![](http://matplotlib.org/_images/mathmpl/math-03cbb97a54.png) `\rightthreetimes` | ![](http://matplotlib.org/_images/mathmpl/math-8f609835cb.png) `\risingdotseq` | 336 | | ![](http://matplotlib.org/_images/mathmpl/math-61a5f3fde0.png) `\rtimes` | ![](http://matplotlib.org/_images/mathmpl/math-10ab63f88f.png) `\sim` | ![](http://matplotlib.org/_images/mathmpl/math-f5e3901a47.png) `\simeq` | 337 | | ![](http://matplotlib.org/_images/mathmpl/math-cd5adea2d9.png) `\slash` | ![](http://matplotlib.org/_images/mathmpl/math-11c6bdf228.png) `\smile` | ![](http://matplotlib.org/_images/mathmpl/math-2fc0f7c957.png) `\sqcap` | 338 | | ![](http://matplotlib.org/_images/mathmpl/math-f3f9a5c2b6.png) `\sqcup` | ![](http://matplotlib.org/_images/mathmpl/math-32710445c4.png) `\sqsubset` | ![](http://matplotlib.org/_images/mathmpl/math-32710445c4.png) `\sqsubset` | 339 | | ![](http://matplotlib.org/_images/mathmpl/math-6462f633f1.png) `\sqsubseteq` | ![](http://matplotlib.org/_images/mathmpl/math-b373234f3b.png) `\sqsupset` | ![](http://matplotlib.org/_images/mathmpl/math-b373234f3b.png) `\sqsupset` | 340 | | ![](http://matplotlib.org/_images/mathmpl/math-301349a96f.png) `\sqsupseteq` | ![](http://matplotlib.org/_images/mathmpl/math-3ea081f1d9.png) `\star` | ![](http://matplotlib.org/_images/mathmpl/math-d7ee7c1348.png) `\subset` | 341 | | ![](http://matplotlib.org/_images/mathmpl/math-ab35a80a37.png) `\subseteq` | ![](http://matplotlib.org/_images/mathmpl/math-329584d288.png) `\subseteqq` | ![](http://matplotlib.org/_images/mathmpl/math-26f9e5316b.png) `\subsetneq` | 342 | | ![](http://matplotlib.org/_images/mathmpl/math-d6c1dc73f3.png) `\subsetneqq` | ![](http://matplotlib.org/_images/mathmpl/math-3b5db3b36b.png) `\succ` | ![](http://matplotlib.org/_images/mathmpl/math-29a7c6603c.png) `\succapprox` | 343 | | ![](http://matplotlib.org/_images/mathmpl/math-764af5d0f7.png) `\succcurlyeq` | ![](http://matplotlib.org/_images/mathmpl/math-f083286645.png) `\succeq` | ![](http://matplotlib.org/_images/mathmpl/math-12e9272240.png) `\succnapprox` | 344 | | ![](http://matplotlib.org/_images/mathmpl/math-22a812f02e.png) `\succnsim` | ![](http://matplotlib.org/_images/mathmpl/math-f313a5f9af.png) `\succsim` | ![](http://matplotlib.org/_images/mathmpl/math-7a88315c05.png) `\supset` | 345 | | ![](http://matplotlib.org/_images/mathmpl/math-b15f9f29ec.png) `\supseteq` | ![](http://matplotlib.org/_images/mathmpl/math-2b42f15859.png) `\supseteqq` | ![](http://matplotlib.org/_images/mathmpl/math-0ebac5d490.png) `\supsetneq` | 346 | | ![](http://matplotlib.org/_images/mathmpl/math-7cafbba6d3.png) `\supsetneqq` | ![](http://matplotlib.org/_images/mathmpl/math-21e977e4ec.png) `\therefore` | ![](http://matplotlib.org/_images/mathmpl/math-ae7023d9db.png) `\times` | 347 | | ![](http://matplotlib.org/_images/mathmpl/math-f0fe2a4a9f.png) `\top` | ![](http://matplotlib.org/_images/mathmpl/math-7a5bdaf004.png) `\triangleleft` | ![](http://matplotlib.org/_images/mathmpl/math-3234da3142.png) `\trianglelefteq` | 348 | | ![](http://matplotlib.org/_images/mathmpl/math-5325d825f0.png) `\triangleq` | ![](http://matplotlib.org/_images/mathmpl/math-61187783ee.png) `\triangleright` | ![](http://matplotlib.org/_images/mathmpl/math-229058201e.png) `\trianglerighteq` | 349 | | ![](http://matplotlib.org/_images/mathmpl/math-8c6a0f04b9.png) `\uplus` | ![](http://matplotlib.org/_images/mathmpl/math-8da9245788.png) `\vDash` | ![](http://matplotlib.org/_images/mathmpl/math-7450111856.png) `\varpropto` | 350 | | ![](http://matplotlib.org/_images/mathmpl/math-311d2647c5.png) `\vartriangleleft` | ![](http://matplotlib.org/_images/mathmpl/math-7da885dcbf.png) `\vartriangleright` | ![](http://matplotlib.org/_images/mathmpl/math-d8ad6ecbe6.png) `\vdash` | 351 | | ![](http://matplotlib.org/_images/mathmpl/math-f5af631a03.png) `\vee` | ![](http://matplotlib.org/_images/mathmpl/math-0ca72c02e5.png) `\veebar` | ![](http://matplotlib.org/_images/mathmpl/math-4c229f580d.png) `\wedge` | 352 | | ![](http://matplotlib.org/_images/mathmpl/math-953993beed.png) `\wr` | 353 | 354 | | 箭头符号 | | | 355 | | --- | --- | --- | 356 | | ![](http://matplotlib.org/_images/mathmpl/math-0c8ba18b43.png) `\Downarrow` | ![](http://matplotlib.org/_images/mathmpl/math-1a6ec6d88f.png) `\Leftarrow` | 357 | | ![](http://matplotlib.org/_images/mathmpl/math-74b9b263f9.png) `\Leftrightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-3ce6141dea.png) `\Lleftarrow` | 358 | | ![](http://matplotlib.org/_images/mathmpl/math-e3d8965f58.png) `\Longleftarrow` | ![](http://matplotlib.org/_images/mathmpl/math-eb3a880058.png) `\Longleftrightarrow` | 359 | | ![](http://matplotlib.org/_images/mathmpl/math-c985be990e.png) `\Longrightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-459d7c5693.png) `\Lsh` | 360 | | ![](http://matplotlib.org/_images/mathmpl/math-0f08e28a07.png) `\Nearrow` | ![](http://matplotlib.org/_images/mathmpl/math-a608a7ae83.png) `\Nwarrow` | 361 | | ![](http://matplotlib.org/_images/mathmpl/math-5e42a40994.png) `\Rightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-317920b703.png) `\Rrightarrow` | 362 | | ![](http://matplotlib.org/_images/mathmpl/math-26fab8f44f.png) `\Rsh` | ![](http://matplotlib.org/_images/mathmpl/math-ba64c5e997.png) `\Searrow` | 363 | | ![](http://matplotlib.org/_images/mathmpl/math-6722d13e60.png) `\Swarrow` | ![](http://matplotlib.org/_images/mathmpl/math-d00ab41d80.png) `\Uparrow` | 364 | | ![](http://matplotlib.org/_images/mathmpl/math-94ff64057f.png) `\Updownarrow` | ![](http://matplotlib.org/_images/mathmpl/math-a59e0fa5ee.png) `\circlearrowleft` | 365 | | ![](http://matplotlib.org/_images/mathmpl/math-ea5765e8b3.png) `\circlearrowright` | ![](http://matplotlib.org/_images/mathmpl/math-68b96a49a5.png) `\curvearrowleft` | 366 | | ![](http://matplotlib.org/_images/mathmpl/math-eb8d6ee4ad.png) `\curvearrowright` | ![](http://matplotlib.org/_images/mathmpl/math-682a5688ef.png) `\dashleftarrow` | 367 | | ![](http://matplotlib.org/_images/mathmpl/math-8bc070eada.png) `\dashrightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-56b7078922.png) `\downarrow` | 368 | | ![](http://matplotlib.org/_images/mathmpl/math-1d11ce50b2.png) `\downdownarrows` | ![](http://matplotlib.org/_images/mathmpl/math-a019dc17a7.png) `\downharpoonleft` | 369 | | ![](http://matplotlib.org/_images/mathmpl/math-16b15cdedd.png) `\downharpoonright` | ![](http://matplotlib.org/_images/mathmpl/math-3db5c70042.png) `\hookleftarrow` | 370 | | ![](http://matplotlib.org/_images/mathmpl/math-580fac9571.png) `\hookrightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-09e354a93e.png) `\leadsto` | 371 | | ![](http://matplotlib.org/_images/mathmpl/math-097464d1cd.png) `\leftarrow` | ![](http://matplotlib.org/_images/mathmpl/math-a2e07eb2ff.png) `\leftarrowtail` | 372 | | ![](http://matplotlib.org/_images/mathmpl/math-792b216977.png) `\leftharpoondown` | ![](http://matplotlib.org/_images/mathmpl/math-3c072a15c0.png) `\leftharpoonup` | 373 | | ![](http://matplotlib.org/_images/mathmpl/math-433174617c.png) `\leftleftarrows` | ![](http://matplotlib.org/_images/mathmpl/math-bce42da457.png) `\leftrightarrow` | 374 | | ![](http://matplotlib.org/_images/mathmpl/math-dec391be07.png) `\leftrightarrows` | ![](http://matplotlib.org/_images/mathmpl/math-8c68333295.png) `\leftrightharpoons` | 375 | | ![](http://matplotlib.org/_images/mathmpl/math-1afd9d2af0.png) `\leftrightsquigarrow` | ![](http://matplotlib.org/_images/mathmpl/math-0a36be904f.png) `\leftsquigarrow` | 376 | | ![](http://matplotlib.org/_images/mathmpl/math-c8fe9fb96c.png) `\longleftarrow` | ![](http://matplotlib.org/_images/mathmpl/math-91b94c6be9.png) `\longleftrightarrow` | 377 | | ![](http://matplotlib.org/_images/mathmpl/math-02ce986a2e.png) `\longmapsto` | ![](http://matplotlib.org/_images/mathmpl/math-80a13771b7.png) `\longrightarrow` | 378 | | ![](http://matplotlib.org/_images/mathmpl/math-3bfe8e8950.png) `\looparrowleft` | ![](http://matplotlib.org/_images/mathmpl/math-64aa42214e.png) `\looparrowright` | 379 | | ![](http://matplotlib.org/_images/mathmpl/math-9a483a288a.png) `\mapsto` | ![](http://matplotlib.org/_images/mathmpl/math-c40f3bc7dc.png) `\multimap` | 380 | | ![](http://matplotlib.org/_images/mathmpl/math-ea5241d5f2.png) `\nLeftarrow` | ![](http://matplotlib.org/_images/mathmpl/math-9119a30630.png) `\nLeftrightarrow` | 381 | | ![](http://matplotlib.org/_images/mathmpl/math-eeabc86e5f.png) `\nRightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-640fa94ebe.png) `\nearrow` | 382 | | ![](http://matplotlib.org/_images/mathmpl/math-f9cc3f8904.png) `\nleftarrow` | ![](http://matplotlib.org/_images/mathmpl/math-1278a024c8.png) `\nleftrightarrow` | 383 | | ![](http://matplotlib.org/_images/mathmpl/math-f11a3eab57.png) `\nrightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-3223454152.png) `\nwarrow` | 384 | | ![](http://matplotlib.org/_images/mathmpl/math-fb1cbbd43f.png) `\rightarrow` | ![](http://matplotlib.org/_images/mathmpl/math-2e03b9e387.png) `\rightarrowtail` | 385 | | ![](http://matplotlib.org/_images/mathmpl/math-41f636a823.png) `\rightharpoondown` | ![](http://matplotlib.org/_images/mathmpl/math-2cdbf2db88.png) `\rightharpoonup` | 386 | | ![](http://matplotlib.org/_images/mathmpl/math-2617106b1e.png) `\rightleftarrows` | ![](http://matplotlib.org/_images/mathmpl/math-2617106b1e.png) `\rightleftarrows` | 387 | | ![](http://matplotlib.org/_images/mathmpl/math-a2eb9bae76.png) `\rightleftharpoons` | ![](http://matplotlib.org/_images/mathmpl/math-a2eb9bae76.png) `\rightleftharpoons` | 388 | | ![](http://matplotlib.org/_images/mathmpl/math-43575c473c.png) `\rightrightarrows` | ![](http://matplotlib.org/_images/mathmpl/math-43575c473c.png) `\rightrightarrows` | 389 | | ![](http://matplotlib.org/_images/mathmpl/math-2aff52a07e.png) `\rightsquigarrow` | ![](http://matplotlib.org/_images/mathmpl/math-93a935b705.png) `\searrow` | 390 | | ![](http://matplotlib.org/_images/mathmpl/math-8d37bd9196.png) `\swarrow` | ![](http://matplotlib.org/_images/mathmpl/math-306ea70acd.png) `\to` | 391 | | ![](http://matplotlib.org/_images/mathmpl/math-ae2fa40b25.png) `\twoheadleftarrow` | ![](http://matplotlib.org/_images/mathmpl/math-8e6cdc7038.png) `\twoheadrightarrow` | 392 | | ![](http://matplotlib.org/_images/mathmpl/math-f1bfb0bbf7.png) `\uparrow` | ![](http://matplotlib.org/_images/mathmpl/math-eb3b3a6d5c.png) `\updownarrow` | 393 | | ![](http://matplotlib.org/_images/mathmpl/math-eb3b3a6d5c.png) `\updownarrow` | ![](http://matplotlib.org/_images/mathmpl/math-bbdf3d8983.png) `\upharpoonleft` | 394 | | ![](http://matplotlib.org/_images/mathmpl/math-5fea7c5657.png) `\upharpoonright` | ![](http://matplotlib.org/_images/mathmpl/math-d831d8aa62.png) `\upuparrows` | 395 | 396 | 397 | | 杂项符号 | | | 398 | | --- | --- | --- | 399 | | ![](http://matplotlib.org/_images/mathmpl/math-390d3dc75c.png) `\$` | ![](http://matplotlib.org/_images/mathmpl/math-7ffb7d798c.png) `\AA` | ![](http://matplotlib.org/_images/mathmpl/math-38501d21c9.png) `\Finv` | 400 | | ![](http://matplotlib.org/_images/mathmpl/math-be84d4168e.png) `\Game` | ![](http://matplotlib.org/_images/mathmpl/math-3207fff524.png) `\Im` | ![](http://matplotlib.org/_images/mathmpl/math-482297a060.png) `\P` | 401 | | ![](http://matplotlib.org/_images/mathmpl/math-6ea3150bfd.png) `\Re` | ![](http://matplotlib.org/_images/mathmpl/math-a99c89f6e1.png) `\S` | ![](http://matplotlib.org/_images/mathmpl/math-2fcd70072d.png) `\angle` | 402 | | ![](http://matplotlib.org/_images/mathmpl/math-9db5c962c8.png) `\backprime` | ![](http://matplotlib.org/_images/mathmpl/math-8082fb34e8.png) `\bigstar` | ![](http://matplotlib.org/_images/mathmpl/math-4b07b72122.png) `\blacksquare` | 403 | | ![](http://matplotlib.org/_images/mathmpl/math-8f8c0c020c.png) `\blacktriangle` | ![](http://matplotlib.org/_images/mathmpl/math-58162c32f0.png) `\blacktriangledown` | ![](http://matplotlib.org/_images/mathmpl/math-e90d63d41d.png) `\cdots` | 404 | | ![](http://matplotlib.org/_images/mathmpl/math-800bb70468.png) `\checkmark` | ![](http://matplotlib.org/_images/mathmpl/math-762c3b5e9e.png) `\circledR` | ![](http://matplotlib.org/_images/mathmpl/math-52eae78384.png) `\circledS` | 405 | | ![](http://matplotlib.org/_images/mathmpl/math-4d24dff6f8.png) `\clubsuit` | ![](http://matplotlib.org/_images/mathmpl/math-b225b29af4.png) `\complement` | ![](http://matplotlib.org/_images/mathmpl/math-8f454df900.png) `\copyright` | 406 | | ![](http://matplotlib.org/_images/mathmpl/math-dbcc77f1d2.png) `\ddots` | ![](http://matplotlib.org/_images/mathmpl/math-bc54d541fc.png) `\diamondsuit` | ![](http://matplotlib.org/_images/mathmpl/math-923c665edb.png) `\ell` | 407 | | ![](http://matplotlib.org/_images/mathmpl/math-51cd44e108.png) `\emptyset` | ![](http://matplotlib.org/_images/mathmpl/math-19f957fc71.png) `\eth` | ![](http://matplotlib.org/_images/mathmpl/math-cac5abe8bf.png) `\exists` | 408 | | ![](http://matplotlib.org/_images/mathmpl/math-518af824c6.png) `\flat` | ![](http://matplotlib.org/_images/mathmpl/math-92a896986d.png) `\forall` | ![](http://matplotlib.org/_images/mathmpl/math-2525d5d71d.png) `\hbar` | 409 | | ![](http://matplotlib.org/_images/mathmpl/math-eab5c7cdff.png) `\heartsuit` | ![](http://matplotlib.org/_images/mathmpl/math-dcb2243778.png) `\hslash` | ![](http://matplotlib.org/_images/mathmpl/math-f8daa97519.png) `\iiint` | 410 | | ![](http://matplotlib.org/_images/mathmpl/math-14a5baf1f1.png) `\iint` | ![](http://matplotlib.org/_images/mathmpl/math-14a5baf1f1.png) `\iint` | ![](http://matplotlib.org/_images/mathmpl/math-6a5f1c0ebd.png) `\imath` | 411 | | ![](http://matplotlib.org/_images/mathmpl/math-c899412e92.png) `\infty` | ![](http://matplotlib.org/_images/mathmpl/math-cca8605565.png) `\jmath` | ![](http://matplotlib.org/_images/mathmpl/math-ee226905c4.png) `\ldots` | 412 | | ![](http://matplotlib.org/_images/mathmpl/math-d78cd804a4.png) `\measuredangle` | ![](http://matplotlib.org/_images/mathmpl/math-07933b21e0.png) `\natural` | ![](http://matplotlib.org/_images/mathmpl/math-21d4b9ec5e.png) `\neg` | 413 | | ![](http://matplotlib.org/_images/mathmpl/math-a01094061c.png) `\nexists` | ![](http://matplotlib.org/_images/mathmpl/math-fea35fa8ec.png) `\oiiint` | ![](http://matplotlib.org/_images/mathmpl/math-7d9222c03b.png) `\partial` | 414 | | ![](http://matplotlib.org/_images/mathmpl/math-d4d8611cbc.png) `\prime` | ![](http://matplotlib.org/_images/mathmpl/math-0525bc07de.png) `\sharp` | ![](http://matplotlib.org/_images/mathmpl/math-799e766e98.png) `\spadesuit` | 415 | | ![](http://matplotlib.org/_images/mathmpl/math-96aad37e82.png) `\sphericalangle` | ![](http://matplotlib.org/_images/mathmpl/math-e51ac520e2.png) `\ss` | ![](http://matplotlib.org/_images/mathmpl/math-62e1ea5660.png) `\triangledown` | 416 | | ![](http://matplotlib.org/_images/mathmpl/math-91a36bab96.png) `\varnothing` | ![](http://matplotlib.org/_images/mathmpl/math-449680794f.png) `\vartriangle` | ![](http://matplotlib.org/_images/mathmpl/math-0716fbd542.png) `\vdots` | 417 | | ![](http://matplotlib.org/_images/mathmpl/math-6eca465169.png) `\wp` | ![](http://matplotlib.org/_images/mathmpl/math-12713adf78.png) `\yen` | 418 | 419 | 如果特定符号没有名称(对于 STIX 字体中的许多较为模糊的符号也是如此),也可以使用 Unicode 字符: 420 | 421 | ```py 422 | ur'$\u23ce$' 423 | ``` 424 | 425 | ## 示例 426 | 427 | 下面是个示例,在上下文中展示了许多这些特性。 428 | 429 | ```py 430 | import numpy as np 431 | import matplotlib.pyplot as plt 432 | t = np.arange(0.0, 2.0, 0.01) 433 | s = np.sin(2*np.pi*t) 434 | 435 | plt.plot(t,s) 436 | plt.title(r'$\alpha_i > \beta_i$', fontsize=20) 437 | plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20) 438 | plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', 439 | fontsize=20) 440 | plt.xlabel('time (s)') 441 | plt.ylabel('volts (mV)') 442 | plt.show() 443 | ``` 444 | 445 | ![](http://matplotlib.org/_images/pyplot_mathtext.png) 446 | 447 | -------------------------------------------------------------------------------- /4.7.md: -------------------------------------------------------------------------------- 1 | # 使用 LaTeX 渲染文本 2 | 3 | > 原文:[Text rendering With LaTeX](http://matplotlib.org/users/usetex.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | Matplotlib 可以选择使用 LaTeX 来管理所有文本布局。 此选项可用于以下后端: 10 | 11 | + Agg 12 | + PS 13 | + PDF 14 | 15 | LaTeX 选项通过在`rc`设置中设置`text.usetex:True`来激活。 使用 matplotlib 的 LaTeX 支持的文本处理会慢于 matplotlib 的非常强大的 mathtext,但是更灵活,因为可以使用不同的 LaTeX 包(字体包,数学包等)。 结果会十分惊人,特别是当你在图形中使用和主文档相同的字体。 16 | 17 | Matplotlib 的 LaTeX 支持需要可用的 LaTeX 安装版本,dvipng(可能包括在你的 LaTeX 安装中)和 Ghostscript(建议使用 GPL Ghostscript 8.60 或更高版本)。 这些外部依赖的可执行文件必须都位于你的`PATH`中。 18 | 19 | 有几个选项需要提及,可以使用`rc`设置更改它们。 这里是一个`matplotlibrc`示例文件: 20 | 21 | 22 | ``` 23 | font.family : serif 24 | font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman 25 | font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif 26 | font.cursive : Zapf Chancery 27 | font.monospace : Courier, Computer Modern Typewriter 28 | 29 | text.usetex : true 30 | ``` 31 | 32 | 每个系列中的第一个有效字体是要加载的字体。 如果未指定字体,则默认使用 Computer Modern 字体。 所有其他字体是 Adobe 字体。 Times 和 Palatino 每个都有自己附带的数学字体,而其他 Adobe 衬线字体使用 Computer Modern 数学字体。 有关更多详细信息,请参阅 [PSNFSS](http://www.ctan.org/tex-archive/macros/latex/required/psnfss/psnfss2e.pdf) 文档。 33 | 34 | 要使用 LaTeX 并选择 Helvetica 作为默认字体,但不编辑`matplotlibrc`,使用: 35 | 36 | ```py 37 | from matplotlib import rc 38 | rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) 39 | ## for Palatino and other serif fonts use: 40 | #rc('font',**{'family':'serif','serif':['Palatino']}) 41 | rc('text', usetex=True) 42 | ``` 43 | 44 | 这里是标准的示例,`tex_demo.py`: 45 | 46 | ```py 47 | """ 48 | Demo of TeX rendering. 49 | 50 | You can use TeX to render all of your matplotlib text if the rc 51 | parameter text.usetex is set. This works currently on the agg and ps 52 | backends, and requires that you have tex and the other dependencies 53 | described at http://matplotlib.org/users/usetex.html 54 | properly installed on your system. The first time you run a script 55 | you will see a lot of output from tex and associated tools. The next 56 | time, the run may be silent, as a lot of the information is cached in 57 | ~/.tex.cache 58 | 59 | """ 60 | import numpy as np 61 | import matplotlib.pyplot as plt 62 | 63 | 64 | # Example data 65 | t = np.arange(0.0, 1.0 + 0.01, 0.01) 66 | s = np.cos(4 * np.pi * t) + 2 67 | 68 | plt.rc('text', usetex=True) 69 | plt.rc('font', family='serif') 70 | plt.plot(t, s) 71 | 72 | plt.xlabel(r'\textbf{time} (s)') 73 | plt.ylabel(r'\textit{voltage} (mV)',fontsize=16) 74 | plt.title(r"\TeX\ is Number " 75 | r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", 76 | fontsize=16, color='gray') 77 | # Make room for the ridiculously large title. 78 | plt.subplots_adjust(top=0.8) 79 | 80 | plt.savefig('tex_demo') 81 | plt.show() 82 | ``` 83 | 84 | ![](http://matplotlib.org/_images/tex_demo.png) 85 | 86 | 要注意数学显示模式(`$$ e=mc^2 $$`)是不支持的,但是添加命令`\displaystyle`之后会产生相同结果,就像`tex_demo.py`中那样。 87 | 88 | > 注意 89 | 90 | > 一些字符在 TeX 中需要特别转义,例如: 91 | 92 | > ``` 93 | > # $ % & ~ _ ^ \ { } \( \) \[ \] 94 | > ``` 95 | 96 | > 所以,这些字符会根据`rcParam text.usetex`标志位而表现不同。 97 | 98 | ## 在 TeX 中使用 Unicode 99 | 100 | 也可以在 LaTeX 文本管理器中使用 unicode 字符串,这里是从`tex_unicode_demo.py`中获取的示例: 101 | 102 | ```py 103 | # -*- coding: utf-8 -*- 104 | """ 105 | This demo is tex_demo.py modified to have unicode. See that file for 106 | more information. 107 | """ 108 | 109 | from __future__ import unicode_literals 110 | import numpy as np 111 | import matplotlib 112 | matplotlib.rcParams['text.usetex'] = True 113 | matplotlib.rcParams['text.latex.unicode'] = True 114 | import matplotlib.pyplot as plt 115 | 116 | plt.figure(1, figsize=(6, 4)) 117 | ax = plt.axes([0.1, 0.1, 0.8, 0.7]) 118 | t = np.arange(0.0, 1.0 + 0.01, 0.01) 119 | s = np.cos(2*2*np.pi*t) + 2 120 | plt.plot(t, s) 121 | 122 | plt.xlabel(r'\textbf{time (s)}') 123 | plt.ylabel('\\textit{Velocity (\u00B0/sec)}', fontsize=16) 124 | plt.title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty' 125 | r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r') 126 | plt.grid(True) 127 | plt.show() 128 | ``` 129 | 130 | ![](http://matplotlib.org/_images/tex_unicode_demo1.png) 131 | 132 | ## Postscript 选项 133 | 134 | 为了生成可以嵌入到新 LaTeX 文档中的 postscript 封装文件,matplotlib 的默认行为是提取输出,这会删除 LaTeX 使用的一些 postscript 操作符,这些操作符在 eps 文件中是非法的。 此步骤产生的结果对于一些用户可能是不可接受的,因为文本被粗略地光栅化并且被转换为位图,而不像标准 Postscript 那样是可缩放的,并且文本是不可搜索的。 一种解决方法是在你的`rc`设置中将`ps.distiller.res`设置为较高的值(可能为 6000),这将产生较大的文件,但可能看起来更好并能够合理缩放。 更好的解决方法需要 Poppler 或 Xpdf,可以通过将`ps.usedistiller rc`设置更改为`xpdf`来激活。 此替代方案产生 postscript 而不光栅化文本,因此它能够正确缩放,可以在 Adobe Illustrator 中编辑,并搜索`pdf`文档中的文本。 135 | 136 | ## 可能的问题 137 | 138 | + 在 Windows 上,可能需要修改[`PATH`](http://matplotlib.org/faq/environment_variables_faq.html#envvar-PATH)环境变量来包含 latex,dvipng 和 ghostscript 可执行文件的目录。详细信息请参阅[环境变量](http://matplotlib.org/faq/environment_variables_faq.html#environment-variables)和[在 Windows 中设置环境变量](http://matplotlib.org/faq/environment_variables_faq.html#setting-windows-environment-variables)。 139 | + 使用 MiKTeX 与 Computer Modern 字体,如果你得到奇怪的 \*Agg 和 PNG 结果,访问`MiKTeX/Options`并更新你的格式文件。 140 | + 字体在屏幕上看起来糟糕。你可能正在运行 Mac OS,在 mac 上的老版本 dvipng 运行着一些有趣的事情。在你的`matplotlibrc`文件中设置`text.dvipnghack:True`。 141 | + 在 Ubuntu 和 Gentoo 上,texlive 基本安装不附带 type1cm 包。你可能需要安装一些额外的包,来获得所有与其它 LaTeX 分发版捆绑的特性。 142 | + matplotlib 已经取得了一些进展,所以可以直接使用`dvi`文件进行文本布局。这允许 LaTeX 用于具有`pdf`和`svg`后端的文本布局,以及 \*Agg 和 PS 后端。在将来,LaTeX 安装可能是唯一的外部依赖。 143 | 144 | ## 故障排除 145 | 146 | + 尝试删除`.matplotlib/tex.cache`目录。 如果你不知道`.matplotlib`在哪里,请参见 [matplotlib 配置和缓存目录位置](http://matplotlib.org/faq/troubleshooting_faq.html#locating-matplotlib-config-dir)。 147 | + 确保 LaTeX,dvipng 和 ghostscript 都正常工作,并存在于你的[`PATH`](http://matplotlib.org/faq/environment_variables_faq.html#envvar-PATH)中。 148 | + 确保你想要做的事情在 LaTeX 文档中可实现,你的 LaTeX 语法是有效的,并且你正在使用原始字符串,如果必要,以避免意外的转义序列。 149 | + 邮件列表上报告的大多数问题已通过升级 [Ghostscript](https://ghostscript.com/) 来清除。 如果可能的话,请尝试升级到最新版本,然后向列表报告问题。 150 | + `text.latex.preamble rc`设置不受官方支持。 此选项提供了大量的灵活性和导致问题的许多方法。 请在向邮件列表报告问题之前禁用此选项。 151 | + 如果仍需要帮助,请参阅[获取帮助](http://matplotlib.org/faq/troubleshooting_faq.html#reporting-problems)。 152 | -------------------------------------------------------------------------------- /4.8.md: -------------------------------------------------------------------------------- 1 | # XeLaTeX/LuaLaTeX 设置 2 | 3 | > 原文:[Typesetting With XeLaTeX/LuaLaTeX](http://matplotlib.org/users/pgf.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 使用 pgf 后端,matplotlib 可以将图形导出为可以使用 pdflatex,xelatex 或 lualatex 处理的 pgf 绘图命令。 XeLaTeX 和 LuaLaTeX 具有完整的 unicode 支持,可以使用安装在操作系统中的任何字体,利用 OpenType,AAT 和 Graphite 的高级排版功能。 由`plt.savefig('figure.pgf')`创建的 Pgf 图片可以作为原始命令嵌入到 LaTeX 文档中。 图形也可以通过切换到该后端,直接编译并使用`plt.savefig('figure.pdf')`保存到 PDF。 10 | 11 | ```py 12 | matplotlib.use('pgf') 13 | ``` 14 | 15 | 或者为处理 PDF 输出而注册它: 16 | 17 | ```py 18 | from matplotlib.backends.backend_pgf import FigureCanvasPgf 19 | matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf) 20 | ``` 21 | 22 | 第二种方法允许你继续使用常规的交互式后端,并从图形用户界面保存 xelatex,lualatex 或 pdflatex 编译的 PDF 文件。 23 | 24 | Matplotlib 的 pgf 支持需要最新的 [LaTeX](http://www.tug.org/) 安装,包括 TikZ/PGF 软件包(如 [TeXLive](http://www.tug.org/texlive/)),最好安装 XeLaTeX 或 LuaLaTeX。 如果你的系统上存在 pdftocairo 或 ghostscript,也可以选择将图形保存为 PNG 图像。 所有应用程序的可执行文件必须位于[`PATH`](http://matplotlib.org/faq/environment_variables_faq.html#envvar-PATH)中。 25 | 26 | 控制 pgf 后端行为的 Rc 参数: 27 | 28 | | 参数 | 文档 | 29 | | --- | --- | 30 | | `pgf.preamble `| 包含在 LaTeX 序言中的行 | 31 | | `pgf.rcfonts` | 使用 fontspec 软件包从 rc 参数设置字体 | 32 | | `pgf.texsystem` | `xelatex`(默认),`lualatex`或者`pdflatex` | 33 | 34 | > 注意 35 | 36 | > TeX 定义了一系列特殊字符,例如: 37 | 38 | > ``` 39 | > # $ % & ~ _ ^ \ { } 40 | > ``` 41 | 42 | > 通常,这些字符必须正确转义。一些字符(`_`,`^`,`%`)会自动在数学环境之外转义。 43 | 44 | ## 字体规定 45 | 46 | 用于获取文本元素大小,或将图形编译为 PDF 的字体通常在 matplotlib rc 参数中定义。 你还可以通过清除`font.serif`,`font.sans-serif`或`font.monospace`的列表来使用 LaTeX 默认的 Computer Modern 字体。 请注意,这些字体的字形覆盖范围非常有限。 如果要保留 Computer Modern 字体,但需要扩展 Unicode 编码支持,请考虑安装 [Computer Modern Unicode](https://sourceforge.net/projects/cm-unicode/) 字体 CMU Serif,CMU Sans Serif 等。 47 | 48 | 保存到`.pgf`时,matplotlib 用于图形布局的字体配置包含在文本文件的标题中。 49 | 50 | ```py 51 | # -*- coding: utf-8 -*- 52 | 53 | import matplotlib as mpl 54 | mpl.use("pgf") 55 | pgf_with_rc_fonts = { 56 | "font.family": "serif", 57 | "font.serif": [], # use latex default serif font 58 | "font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font 59 | } 60 | mpl.rcParams.update(pgf_with_rc_fonts) 61 | 62 | import matplotlib.pyplot as plt 63 | plt.figure(figsize=(4.5,2.5)) 64 | plt.plot(range(5)) 65 | plt.text(0.5, 3., "serif") 66 | plt.text(0.5, 2., "monospace", family="monospace") 67 | plt.text(2.5, 2., "sans-serif", family="sans-serif") 68 | plt.text(2.5, 1., "comic sans", family="Comic Sans MS") 69 | plt.xlabel(u"μ is not $\\mu$") 70 | plt.tight_layout(.5) 71 | ``` 72 | 73 | ![](http://matplotlib.org/_images/pgf_fonts.png) 74 | 75 | ## 自定义序言 76 | 77 | 通过将你的命令添加到序言中,你可以完全自定义它。 如果要配置数学字体(例如使用 unicode-math)或加载其他软件包,请使用`pgf.preamble`参数。 此外,如果你想自己做字体配置,而不是使用 rc 参数中指定的字体,请确保禁用`pgf.rcfonts`。 78 | 79 | ```py 80 | # -*- coding: utf-8 -*- 81 | from __future__ import (absolute_import, division, print_function, 82 | unicode_literals) 83 | 84 | import six 85 | 86 | import matplotlib as mpl 87 | mpl.use("pgf") 88 | pgf_with_custom_preamble = { 89 | "font.family": "serif", # use serif/main font for text elements 90 | "text.usetex": True, # use inline math for ticks 91 | "pgf.rcfonts": False, # don't setup fonts from rc parameters 92 | "pgf.preamble": [ 93 | "\\usepackage{units}", # load additional packages 94 | "\\usepackage{metalogo}", 95 | "\\usepackage{unicode-math}", # unicode math setup 96 | r"\setmathfont{xits-math.otf}", 97 | r"\setmainfont{DejaVu Serif}", # serif font via preamble 98 | ] 99 | } 100 | mpl.rcParams.update(pgf_with_custom_preamble) 101 | 102 | import matplotlib.pyplot as plt 103 | plt.figure(figsize=(4.5,2.5)) 104 | plt.plot(range(5)) 105 | plt.xlabel("unicode text: я, ψ, €, ü, \\unitfrac[10]{°}{μm}") 106 | plt.ylabel("\\XeLaTeX") 107 | plt.legend(["unicode math: $λ=∑_i^∞ μ_i^2$"]) 108 | plt.tight_layout(.5) 109 | ``` 110 | 111 | ![](http://matplotlib.org/_images/pgf_preamble.png) 112 | 113 | ## 选择 TeX 系统 114 | 115 | matplotlib 使用的 TeX 系统由`pgf.texsystem`参数选择。 可能的值为`xelatex`(默认值),`lualatex`和`pdflatex`。 请注意,当选择`pdflatex`时,必须在序言中配置字体和 unicode 处理。 116 | 117 | ```py 118 | # -*- coding: utf-8 -*- 119 | 120 | import matplotlib as mpl 121 | mpl.use("pgf") 122 | pgf_with_pdflatex = { 123 | "pgf.texsystem": "pdflatex", 124 | "pgf.preamble": [ 125 | r"\usepackage[utf8x]{inputenc}", 126 | r"\usepackage[T1]{fontenc}", 127 | r"\usepackage{cmbright}", 128 | ] 129 | } 130 | mpl.rcParams.update(pgf_with_pdflatex) 131 | 132 | import matplotlib.pyplot as plt 133 | plt.figure(figsize=(4.5,2.5)) 134 | plt.plot(range(5)) 135 | plt.text(0.5, 3., "serif", family="serif") 136 | plt.text(0.5, 2., "monospace", family="monospace") 137 | plt.text(2.5, 2., "sans-serif", family="sans-serif") 138 | plt.xlabel(u"μ is not $\\mu$") 139 | plt.tight_layout(.5) 140 | ``` 141 | 142 | ![](http://matplotlib.org/_images/pgf_texsystem.png) 143 | 144 | ## 故障排除 145 | 146 | 请注意,在一些 Linux 发行版和 MiKTeX 安装中发现的 TeX 包已经过时了。确保更新你的软件包目录并升级或安装最新的 TeX 发行版。 147 | 在 Windows 上,可能需要修改[`PATH`](http://matplotlib.org/faq/environment_variables_faq.html#envvar-PATH)环境变量来包含 latex,dvipng 和 ghostscript 可执行文件的目录。详细信息请参阅[环境变量](http://matplotlib.org/faq/environment_variables_faq.html#environment-variables)和[在窗口中设置环境变量](http://matplotlib.org/faq/environment_variables_faq.html#setting-windows-environment-variables)。 148 | Windows 上的限制会导致后端保留由应用程序打开的文件句柄。因此,可能无法删除相应的文件,直到应用程序关闭(参见[`#1324`](https://github.com/matplotlib/matplotlib/issues/1324))。 149 | 有时保存到 png 图像的图形中的字体非常糟糕。这在 pdftocairo 工具不可用,并且 ghostscript 用于 pdf 到 png 的转换时发生。 150 | 确保你想要做的事情在 LaTeX 文档中可实现,你的 LaTeX 语法是有效的,并且你正在使用原始字符串,如果必要的话,避免意外的转义序列。 151 | `pgf.preamble rc`设置提供了大量的灵活性,以及导致问题的许多方法。遇到问题时,尝试最小化或禁用自定义序言。 152 | 配置 unicode-math 环境可能有点棘手。例如 TeXLive 分发版提供了一组通常不在系统范围内安装的数学字体。与 LuaLatex 不同的是,XeTeX 不能根据名字找到这些字体,这就是你可能必须指定`\setmathfont{xits-math.otf}`,而不是`\setmathfont{XITS Math}`的原因,或者使字体可用于你的操作系统。更多详细信息请参阅这个[`tex.stackexchange.com`的问题](http://tex.stackexchange.com/questions/43642)。 153 | 如果 matplotlib 使用的字体配置不同于你的 LaTeX 文档中的字体设置,则导入图形中的文本元素对齐可能会关闭。如果你不确定 matplotlib 用于布局的字体,请检查`.pgf`文件的标题。 154 | 如果图中有很多对象,矢量图像和`.pgf`文件可能变得臃肿。这可能是图像处理或非常大的散点图的情况。在极端情况下,这可能导致 TeX 内存不足:`TeX capacity exceeded, sorry`(TeX 容量过大,对不起)。你可以配置 LaTeX 来增加可用于生成`.pdf`图像的内存量,请见[`tex.stackexchange.com`](http://tex.stackexchange.com/questions/7953)上讨论的问题。另一种方法是使用`rasterized = True`关键字,或者根据[本示例](http://matplotlib.org/examples/misc/rasterization_demo.html)的`.set_rasterized(True)`『栅格化』图形的某些导致问题部分。 155 | 如果你仍需要帮助,请参阅[获取帮助](http://matplotlib.org/faq/troubleshooting_faq.html#reporting-problems)。 156 | -------------------------------------------------------------------------------- /4.md: -------------------------------------------------------------------------------- 1 | # 文本处理 -------------------------------------------------------------------------------- /5.1.md: -------------------------------------------------------------------------------- 1 | # 指定颜色 2 | 3 | > 原文:[Specifying Colors](http://matplotlib.org/users/colors.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 在 matplotlib 的几乎所有地方,用户都可以指定颜色,它可以以如下形式提供: 10 | 11 | + RGB 或者 RGBA 浮点值元组,`[0, 1]`之间,例如`(0.1, 0.2, 0.5)`或者`(0.1, 0.2, 0.5, 0.3)`。 12 | 13 | + RGB 或者 RGBA 十六进制字符串,例如`#0F0F0F`或者`#0F0F0F0F`。 14 | 15 | + `[0, 1]`之间的浮点值的字符串表示,用于表示灰度,例如`0.5`。 16 | 17 | + `{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}`之一。 18 | 19 | + X11/CSS4 颜色名称。 20 | 21 | + [XKCD 颜色](https://xkcd.com/color/rgb/)之一,以`'xkcd:'`为前缀,例如`'xkcd:sky blue'`。 22 | 23 | + `{'C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'}`之一。 24 | 25 | + `{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}`之一。这是 T10 调色板的 Tableau 颜色(默认的色相环)。 26 | 27 | 所有颜色字符串都是大小写敏感的。 28 | 29 | ## `CN`颜色选择 30 | 31 | 颜色可以通由匹配正则表达式`C[0-9]`的字符串来指定。 这可以在任何当前接受颜色的地方传递,并且可以在`matplotlib.Axes.plot`的`format-string`中用作“单个字符颜色”。 32 | 33 | 单个数字是默认属性环的索引(`matplotlib.rcParams['axes.prop_cycle']`)。 如果属性环不包括`'color'`,则返回黑色。 在创建艺术家时会对颜色求值。 例如: 34 | 35 | ```py 36 | import numpy as np 37 | import matplotlib.pyplot as plt 38 | import matplotlib as mpl 39 | th = np.linspace(0, 2*np.pi, 128) 40 | 41 | def demo(sty): 42 | mpl.style.use(sty) 43 | fig, ax = plt.subplots(figsize=(3, 3)) 44 | 45 | ax.set_title('style: {!r}'.format(sty), color='C0') 46 | 47 | ax.plot(th, np.cos(th), 'C1', label='C1') 48 | ax.plot(th, np.sin(th), 'C2', label='C2') 49 | ax.legend() 50 | 51 | demo('default') 52 | ``` 53 | 54 | ![](http://matplotlib.org/_images/colors-1_00.png) 55 | 56 | ![](http://matplotlib.org/_images/colors-1_01.png) 57 | -------------------------------------------------------------------------------- /5.2.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wizardforcel/matplotlib-user-guide-zh/7036a15a620220090b648997d1c93972f095fffa/5.2.md -------------------------------------------------------------------------------- /5.3.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wizardforcel/matplotlib-user-guide-zh/7036a15a620220090b648997d1c93972f095fffa/5.3.md -------------------------------------------------------------------------------- /5.md: -------------------------------------------------------------------------------- 1 | # 颜色 -------------------------------------------------------------------------------- /6.md: -------------------------------------------------------------------------------- 1 | # 自定义 matplotlib 2 | 3 | > 原文:[Customizing matplotlib](http://matplotlib.org/users/customizing.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | ## 使用样式表自定义绘图 10 | 11 | `style`包为易于切换的绘图『样式』增加了支持,它们与`matplotlibrc`文件参数相同。 12 | 13 | 有一些预定义样式由`matplotlib`提供。 例如,有一个名为『ggplot』的预定义样式,它模拟`ggplot`(R 的一种流行的绘图软件包)的美学。 为了使用此样式,只需添加: 14 | 15 | ```py 16 | >>> import matplotlib.pyplot as plt 17 | >>> plt.style.use('ggplot') 18 | ``` 19 | 20 | 为了列出所有可用样式,使用: 21 | 22 | ```py 23 | >>> print(plt.style.available) 24 | ``` 25 | 26 | ## 定义你自己的样式 27 | 28 | 你可以创建自定义样式,并通过以样式表的路径或 URL 调用`style.use`来使用它们。 或者,如果将` mplstyle`文件添加到`mpl_configdir /stylelib`中,你可以通过调用`style.use()`重复使用自定义样式表。 默认情况下`mpl_configdir`应该是`~/.config/matplotlib`,但你可以使用`matplotlib.get_configdir()`检查你的位置,你可能需要创建这个目录。 请注意,如果样式具有相同的名称,`mpl_configdir/stylelib`中的自定义样式表将覆盖由`matplotlib`定义的样式表。 29 | 30 | 例如,你可能想要使用以下命令创建`mpl_configdir/stylelib/presentation.mplstyle`: 31 | 32 | ``` 33 | axes.titlesize : 24 34 | axes.labelsize : 20 35 | lines.linewidth : 3 36 | lines.markersize : 10 37 | xtick.labelsize : 16 38 | ytick.labelsize : 16 39 | ``` 40 | 41 | 然后,当你想要将一个为纸张设计的地图迁移到演示文档中时,你可以添加: 42 | 43 | ```py 44 | >>> import matplotlib.pyplot as plt 45 | >>> plt.style.use('presentation') 46 | ``` 47 | 48 | ## 组合样式 49 | 50 | 样式表为组合在一起而设计。 因此,你可以拥有一个自定义颜色的样式表和一个单独的样式表,用于更改演示文档的元素大小。 这些样式可以通过传递样式列表轻松组合: 51 | 52 | ```py 53 | >>> import matplotlib.pyplot as plt 54 | >>> plt.style.use(['dark_background', 'presentation']) 55 | ``` 56 | 57 | 请注意,右侧的样式将覆盖已经由左侧样式定义的值。 58 | 59 | ## 临时样式 60 | 61 | 如果只想对特定的代码块使用样式,但不想更改全局样式,那么样式包提供了一个上下文管理器,用于将更改限制于特定范围。 要隔离你的样式更改,你可以编写以下内容: 62 | 63 | ```py 64 | >>> import numpy as np 65 | >>> import matplotlib.pyplot as plt 66 | >>> 67 | >>> with plt.style.context(('dark_background')): 68 | >>> plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o') 69 | >>> 70 | >>> # Some plotting code with the default style 71 | >>> 72 | >>> plt.show() 73 | ``` 74 | -------------------------------------------------------------------------------- /7.1.md: -------------------------------------------------------------------------------- 1 | # 交互式导航 2 | 3 | > 原文:[Interactive navigation](http://matplotlib.org/users/navigation_toolbar.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | ![](http://matplotlib.org/_images/toolbar.png) 10 | 11 | 所有图形窗口都带有导航工具栏,可用于浏览数据集。 以下是工具栏底部的每个按钮的说明: 12 | 13 | ![](http://matplotlib.org/_images/back.png) 14 | 15 | `Home`(首页)、`Forward`(前进)和`Back`(后退)按钮: 16 | 17 | 这些类似于 Web 浏览器的前进和后退按钮。 它们用于在之前定义的视图之间来回浏览。 它们没有意义,除非你已经使用平移和缩放按钮访问了其他地方。 这类似于尝试在访问新页面之前单击 Web 浏览器上的返回 - 什么都不会发生。 首页总是你第一个浏览的页面,以及你的数据的默认视图。 对于`Home`,`Forward`和`Back`,应该将其看做 Web浏览器,其中的数据视图是网页。 使用`Pan`和`Zoom`来定义新视图。 18 | 19 | ![](http://matplotlib.org/_images/move.png) 20 | 21 | `Pan/Zoom`(平移/缩放)按钮 22 | 23 | 此按钮有两种模式:平移和缩放。 单击工具栏按钮激活平移和缩放,然后将鼠标放在轴域的某个地方。 按住鼠标左键并将其拖动到新位置来平移图形。 当你释放它时,你按下的点处的数据将移动到你释放的点。 如果在平移时按`'x'`或`'y'`,移动会分别限制在`x`或`y`轴。 按鼠标右键并将其拖动到新位置来进行缩放。 向右移动使`x`轴成比例放大,或者向左移动成比例缩小。 `y`轴和上/下移动同上。 开始缩放时鼠标下的点会保持静止,你可以缩放图形中的其它任意点。 你可以使用快捷键`'x'`,`'y'`或`CONTROL`分别将缩放约束为`x`轴,`y`轴或保留宽高比。 24 | 25 | 使用极坐标绘图时,平移和缩放功能的行为不同。 可以使用鼠标左键拖动半径轴标签。 可以使用鼠标右键放大和缩小半径刻度。 26 | 27 | ![](http://matplotlib.org/_images/zoom_to_rect.png) 28 | 29 | `Zoom-to-rectangle`(缩放到矩形)按钮 30 | 31 | 单击此工具栏按钮以激活此模式。 将鼠标放在轴域的某处,然后按鼠标左键。 在按住按钮的同时拖动鼠标到新位置并释放。 轴域会放大并限制于你定义的矩形。 在此模式中还有一个实验性的`zoom out to rectangle`(缩小到矩形),使用右键,将整个轴域缩小并放置在矩形定义的区域中。 32 | 33 | ![](http://matplotlib.org/_images/subplots.png) 34 | 35 | `Subplot-configuration`(子图配置)按钮 36 | 37 | 使用此工具配置子图的参数:左边距,右边距,上边距,下边距,行间隔和列间隔。 38 | 39 | ![](http://matplotlib.org/_images/filesave.png) 40 | 41 | `Save`(保存)按钮 42 | 43 | 单击此按钮可启动文件保存对话框。 你可以使用以下扩展名保存文件:`png`,`ps`,`eps`,`svg`和`pdf`。 44 | 45 | ## 浏览快捷键 46 | 47 | 下表包含所有默认的快捷键,可以使用`matplotlibrc`(`#keymap.*`)覆盖。 48 | 49 | | 命令 | 快捷键 | 50 | | --- | --- | 51 | | 主页/重置 | `h`、`r`或`home` | 52 | | 后退 | `c`、左箭头或`backspace` | 53 | | 前进 | `v`或右箭头 | 54 | | 平移/缩放 | `p` | 55 | | 缩放到矩形 | `o` | 56 | | 保存 | `ctrl + s` | 57 | | 切换全屏 | `ctrl + f` | 58 | | 关闭绘图 | `ctrl + w` | 59 | | 将平移/缩放限制于`x`轴 | 使用鼠标平移/缩放时按住`x` | 60 | | 将平移/缩放限制于`y`轴 | 使用鼠标平移/缩放时按住`y` | 61 | | 保留宽高比 | 使用鼠标平移/缩放时按住`CONTROL` | 62 | | 切换网格 | 鼠标在轴域上时按下`g` | 63 | | 切换`x`轴刻度(对数/线性) | 鼠标在轴域上时按下`L`或`k` | 64 | | 切换`y`轴刻度(对数/线性) | 鼠标在轴域上时按下`l` | 65 | 66 | 如果你使用`matplotlib.pyplot`,则会为每个图形自动创建工具栏。 如果你正在编写自己的用户界面代码,则可以将工具栏添加为窗口小部件。 确切的语法取决于你的 UI,但在`matplotlib/examples/user_interfaces目录中有每个受支持的 UI 的示例。 这里是一些 GTK 的示例代码: 67 | 68 | ```py 69 | import gtk 70 | 71 | from matplotlib.figure import Figure 72 | from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas 73 | from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar 74 | 75 | win = gtk.Window() 76 | win.connect("destroy", lambda x: gtk.main_quit()) 77 | win.set_default_size(400,300) 78 | win.set_title("Embedding in GTK") 79 | 80 | vbox = gtk.VBox() 81 | win.add(vbox) 82 | 83 | fig = Figure(figsize=(5,4), dpi=100) 84 | ax = fig.add_subplot(111) 85 | ax.plot([1,2,3]) 86 | 87 | canvas = FigureCanvas(fig) # a gtk.DrawingArea 88 | vbox.pack_start(canvas) 89 | toolbar = NavigationToolbar(canvas, win) 90 | vbox.pack_start(toolbar, False, False) 91 | 92 | win.show_all() 93 | gtk.main() 94 | ``` 95 | -------------------------------------------------------------------------------- /7.2.md: -------------------------------------------------------------------------------- 1 | # 在 Python shell 中使用 Matplotlib 2 | 3 | > 原文:[Using matplotlib in a python shell](http://matplotlib.org/users/shell.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | > 警告 10 | 11 | > 该页面的内容已严重过时。 12 | 13 | 默认情况下,matplotlib 将绘图延迟到脚本结束,因为绘图可能是开销大的操作,并且你可能不想在每次更改单个属性时更新绘图,而是只在所有属性更改后更新一次。 14 | 15 | 但是在 python shell 中工作时,通常需要用每个命令更新绘图,例如,在更改`xlabel()`或一行的标记样式之后。 虽然这在概念上很简单,但在实践中它可能很棘手,因为 matplotlib 在底层是一个图形用户界面应用程序,并拥有一些技巧,使应用程序在一个 python shell 正常工作。 16 | 17 | ## 使用 IPython 解决 18 | 19 | > 注意 20 | 21 | > 这里描述的模式出于历史原因仍然存在,但强烈建议不要使用。它污染函数的命名空间,会影响 python 内建设施,并可能导致错误难以跟踪。 要获得 IPython 集成而无需导入,使用`%matplotlib`魔术命令是首个选择。 参见 [ipython 文档](http://ipython.org/ipython-doc/stable/interactive/reference.html#plotting-with-matplotlib)。 22 | 23 | 幸运的是,一个增强的交互式 python shell,[ipython](http://ipython.org/) 已经找出了所有这些技巧,并且可被 matplotlib 感知,所以当你在 pylab 模式下启动 ipython。 24 | 25 | ``` 26 | johnh@flag:~> ipython 27 | Python 2.4.5 (#4, Apr 12 2008, 09:09:16) 28 | IPython 0.9.0 -- An enhanced Interactive Python. 29 | 30 | In [1]: %pylab 31 | 32 | Welcome to pylab, a matplotlib-based Python environment. 33 | For more information, type 'help(pylab)'. 34 | 35 | In [2]: x = randn(10000) 36 | 37 | In [3]: hist(x, 100) 38 | ``` 39 | 40 | 它为你设置一切使交互式绘图工作,就像你期望的那样。 调用`figure()`并弹出图形窗口,调用`plot()`使你的数据出现在图形窗口中。 41 | 42 | 注意在上面的例子中,我们没有导入任何 matplotlib 名称,因为在 pylab 模式下,ipython 将自动导入它们。 ipython 还为你启用交互模式,这会导致每个 pyplot 命令触发图形更新,并且还提供了一个 matplotlib 感知的运行命令,来高效运行 matplotlib 脚本。 ipython 在运行命令期间关闭交互模式,然后在运行结束时恢复交互状态,以便你可以手动继续调整图形。 43 | 44 | ipython 已经嵌入了很多最近的作品,从 pylab 支持,到各种 GUI 应用程序,所以请检查 ipython 邮件列表的最新状态。 45 | 46 | ## 其它 Python 解释器 47 | 48 | 如果你不能使用 ipython,并且仍然想在交互式 python shell 使用 matplotlib/pylab,例如,plain-ole 标准的 python 交互式解释器,你将需要了解[什么是 matplotlib 后端](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend) 。 49 | 50 | 有了 TkAgg 后端,它使用 Tkinter 用户界面工具包,你可以从任意的非 gui python shell 使用 matplotlib。 只需在你的`matplotlibrc`文件中设置`backend : TkAgg `和`interactive : True `(请参阅自定义 matplotlib)并启动 python。 然后: 51 | 52 | ```py 53 | >>> from pylab import * 54 | >>> plot([1,2,3]) 55 | >>> xlabel('hi mom') 56 | ``` 57 | 58 | 应该能够开箱即用。 这也可能适用于最新版本的 qt4agg 和 gtkagg 后端,以及 Macintosh 上的 macosx 后端。 注意,在批处理模式下,即从脚本制作图形时,交互模式可能很慢,因为它用每个命令重绘图形。 因此,你可能需要仔细考虑,然后通过`matplotlibrc`文件而不是使用下一节中列出的函数,使其作为默认行为。 59 | 60 | Gui shell 问题最多,因为它们必须运行主循环,但是交互式绘图也涉及主循环。 Ipython 已经为 matplotlib 主后端解决了这一切问题。 可能有其他 shell 和 IDE 也可以在交互模式下使用 matplotlib,但一个明显的候选项不会:python IDLE IDE 是一个不支持 pylab 交互模式的 Tkinter gui 应用程序,无论后端是什么。 61 | 62 | ## 控制交互式更新 63 | 64 | `pyplot`接口的`interactive`属性控制是否在每个`pyplot`命令上绘制图画布。 如果`interactive`是`False`,那么每个`plot`命令都会更新图形状态,但只会在显式调用`draw()`时绘制。 当`interactive`为`True`时,每个`pyplot`命令都会触发绘制。 65 | 66 | `pyplot`接口提供了 4 个有助于交互式控制的命令。 67 | 68 | `isinteractive()` 69 | 70 | 返回交互式设置。`True|False`。 71 | 72 | `ion()` 73 | 74 | 将交互式模式打开。 75 | 76 | `ioff()` 77 | 78 | 将交互式模式关闭。 79 | 80 | `draw()` 81 | 82 | 强制图形重新绘制。 83 | 84 | 当处理绘图开销很大的大型图形时,你可能希望临时关闭 matplotlib 的交互式设置来避免性能损失: 85 | 86 | ```py 87 | >>> #create big-expensive-figure 88 | >>> ioff() # turn updates off 89 | >>> title('now how much would you pay?') 90 | >>> xticklabels(fontsize=20, color='green') 91 | >>> draw() # force a draw 92 | >>> savefig('alldone', dpi=300) 93 | >>> close() 94 | >>> ion() # turn updating back on 95 | >>> plot(rand(20), mfc='g', mec='r', ms=40, mew=4, ls='--', lw=3) 96 | ``` 97 | -------------------------------------------------------------------------------- /7.3.md: -------------------------------------------------------------------------------- 1 | # 事件处理及拾取 2 | 3 | > 原文:[Event handling and picking](http://matplotlib.org/users/event_handling.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | matplotlib 使用了许多用户界面工具包(wxpython,tkinter,qt4,gtk 和 macosx),为了支持交互式平移和缩放图形等功能,拥有一套 API 通过按键和鼠标移动与图形交互,并且『GUI中立』,对开发人员十分有帮助,所以我们不必重复大量的代码来跨不同的用户界面。虽然事件处理 API 是 GUI 中立的,但它是基于 GTK 模型,这是 matplotlib 支持的第一个用户界面。与标准 GUI 事件相比,被触发的事件也比 matplotlib 丰富一些,例如包括发生事件的`matplotlib.axes.Axes`的信息。事件还能够理解 matplotlib 坐标系,并且在事件中以像素和数据坐标为单位报告事件位置。 10 | 11 | ## 事件连接 12 | 13 | 要接收事件,你需要编写一个回调函数,然后将你的函数连接到事件管理器,它是`FigureCanvasBase`的一部分。这是一个简单的例子,打印鼠标点击的位置和按下哪个按钮: 14 | 15 | ```py 16 | fig = plt.figure() 17 | ax = fig.add_subplot(111) 18 | ax.plot(np.random.rand(10)) 19 | 20 | def onclick(event): 21 | print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % 22 | (event.button, event.x, event.y, event.xdata, event.ydata)) 23 | 24 | cid = fig.canvas.mpl_connect('button_press_event', onclick) 25 | ``` 26 | 27 | `FigureCanvas`的方法`mpl_connect()`返回一个连接`id`,它只是一个整数。 当你要断开回调时,只需调用: 28 | 29 | ```py 30 | fig.canvas.mpl_disconnect(cid) 31 | ``` 32 | 33 | > 注意 34 | 35 | > 画布仅保留回调的弱引用。 因此,如果回调是类实例的方法,你需要保留对该实例的引用。 否则实例将被垃圾回收,回调将消失。 36 | 37 | 以下是可以连接到的事件,在事件发生时发回给你的类实例以及事件描述: 38 | 39 | | 事件名称 | 类和描述 | 40 | | --- | --- | --- | 41 | | `'button_press_event'` | `MouseEvent` - 鼠标按钮被按下 | 42 | | `'button_release_event'` | `MouseEvent` - 鼠标按钮被释放 | 43 | | `'draw_event'` | `DrawEvent` - 画布绘图 | 44 | | `'key_press_event'` | `KeyEvent` - 按键被按下 | 45 | | `'key_release_event'` | `KeyEvent` - 按键被释放 | 46 | | `'motion_notify_event'` | `MouseEvent` - 鼠标移动 | 47 | | `'pick_event'` | `PickEvent` - 画布中的对象被选中 | 48 | | `'resize_event'` | `ResizeEvent` - 图形画布大小改变 | 49 | | `'scroll_event'` | `MouseEvent` - 鼠标滚轮被滚动 | 50 | | `'figure_enter_event'` | `LocationEvent` - 鼠标进入新的图形 | 51 | | `'figure_leave_event'` | `LocationEvent` - 鼠标离开图形 | 52 | | `'axes_enter_event'` | `LocationEvent` - 鼠标进入新的轴域 | 53 | | `'axes_leave_event'` | `LocationEvent` - 鼠标离开轴域 | 54 | 55 | ## 事件属性 56 | 57 | 所有 matplotlib 事件继承自基类`matplotlib.backend_bases.Event`,储存以下属性: 58 | 59 | `name` 60 | 61 | 事件名称 62 | 63 | `canvas` 64 | 65 | 生成事件的`FigureCanvas `实例 66 | 67 | `guiEvent` 68 | 69 | 触发 matplotlib 事件的 GUI 事件 70 | 71 | 最常见的事件是按键按下/释放事件、鼠标按下/释放和移动事件。 处理这些事件的`KeyEvent`和`MouseEvent`类都派生自`LocationEvent`,它具有以下属性: 72 | 73 | `x` 74 | 75 | x 位置,距离画布左端的像素 76 | 77 | `y` 78 | 79 | y 位置,距离画布底端的像素 80 | 81 | `inaxes` 82 | 83 | 如果鼠标经过轴域,则为`Axes`实例 84 | 85 | `xdata` 86 | 87 | 鼠标的`x`坐标,以数据坐标为单位 88 | 89 | `ydata` 90 | 91 | 鼠标的`y`坐标,以数据坐标为单位 92 | 93 | 但我们看一看画布的简单示例,其中每次按下鼠标时都会创建一条线段。 94 | 95 | ```py 96 | from matplotlib import pyplot as plt 97 | 98 | class LineBuilder: 99 | def __init__(self, line): 100 | self.line = line 101 | self.xs = list(line.get_xdata()) 102 | self.ys = list(line.get_ydata()) 103 | self.cid = line.figure.canvas.mpl_connect('button_press_event', self) 104 | 105 | def __call__(self, event): 106 | print('click', event) 107 | if event.inaxes!=self.line.axes: return 108 | self.xs.append(event.xdata) 109 | self.ys.append(event.ydata) 110 | self.line.set_data(self.xs, self.ys) 111 | self.line.figure.canvas.draw() 112 | 113 | fig = plt.figure() 114 | ax = fig.add_subplot(111) 115 | ax.set_title('click to build line segments') 116 | line, = ax.plot([0], [0]) # empty line 117 | linebuilder = LineBuilder(line) 118 | 119 | plt.show() 120 | ``` 121 | 122 | 我们刚刚使用的`MouseEvent`是一个`LocationEvent`,因此我们可以访问`event.x`和`event.xdata`中的数据和像素坐标。 除了`LocationEvent`属性,它拥有: 123 | 124 | `button` 125 | 126 | 按下的按钮,`None`、1、2、3、`'up'`、`'down'`(`'up'`、`'down'`用于滚动事件) 127 | 128 | `key` 129 | 130 | 按下的键,`None`,任何字符,`'shift'`、`'win'`或者`'control'` 131 | 132 | ### 可拖拽的矩形练习 133 | 134 | 编写使用`Rectangle`实例初始化的可拖动矩形类,但在拖动时会移动其`x`,`y`位置。 提示:你需要存储矩形的原始`xy`位置,存储为`rect.xy`并连接到按下,移动和释放鼠标事件。 当鼠标按下时,检查点击是否发生在你的矩形上(见`matplotlib.patches.Rectangle.contains()`),如果是,存储矩形`xy`和数据坐标为单位的鼠标点击位置。 在移动事件回调中,计算鼠标移动的`deltax`和`deltay`,并将这些增量添加到存储的原始矩形,并重新绘图。 在按钮释放事件中,只需将所有你存储的按钮按下数据重置为`None`。 135 | 136 | 这里是解决方案: 137 | 138 | ```py 139 | import numpy as np 140 | import matplotlib.pyplot as plt 141 | 142 | class DraggableRectangle: 143 | def __init__(self, rect): 144 | self.rect = rect 145 | self.press = None 146 | 147 | def connect(self): 148 | 'connect to all the events we need' 149 | self.cidpress = self.rect.figure.canvas.mpl_connect( 150 | 'button_press_event', self.on_press) 151 | self.cidrelease = self.rect.figure.canvas.mpl_connect( 152 | 'button_release_event', self.on_release) 153 | self.cidmotion = self.rect.figure.canvas.mpl_connect( 154 | 'motion_notify_event', self.on_motion) 155 | 156 | def on_press(self, event): 157 | 'on button press we will see if the mouse is over us and store some data' 158 | if event.inaxes != self.rect.axes: return 159 | 160 | contains, attrd = self.rect.contains(event) 161 | if not contains: return 162 | print('event contains', self.rect.xy) 163 | x0, y0 = self.rect.xy 164 | self.press = x0, y0, event.xdata, event.ydata 165 | 166 | def on_motion(self, event): 167 | 'on motion we will move the rect if the mouse is over us' 168 | if self.press is None: return 169 | if event.inaxes != self.rect.axes: return 170 | x0, y0, xpress, ypress = self.press 171 | dx = event.xdata - xpress 172 | dy = event.ydata - ypress 173 | #print('x0=%f, xpress=%f, event.xdata=%f, dx=%f, x0+dx=%f' % 174 | # (x0, xpress, event.xdata, dx, x0+dx)) 175 | self.rect.set_x(x0+dx) 176 | self.rect.set_y(y0+dy) 177 | 178 | self.rect.figure.canvas.draw() 179 | 180 | 181 | def on_release(self, event): 182 | 'on release we reset the press data' 183 | self.press = None 184 | self.rect.figure.canvas.draw() 185 | 186 | def disconnect(self): 187 | 'disconnect all the stored connection ids' 188 | self.rect.figure.canvas.mpl_disconnect(self.cidpress) 189 | self.rect.figure.canvas.mpl_disconnect(self.cidrelease) 190 | self.rect.figure.canvas.mpl_disconnect(self.cidmotion) 191 | 192 | fig = plt.figure() 193 | ax = fig.add_subplot(111) 194 | rects = ax.bar(range(10), 20*np.random.rand(10)) 195 | drs = [] 196 | for rect in rects: 197 | dr = DraggableRectangle(rect) 198 | dr.connect() 199 | drs.append(dr) 200 | 201 | plt.show() 202 | ``` 203 | 204 | 附加题:使用动画秘籍中讨论的动画 blit 技术,使动画绘制更快更流畅。 205 | 206 | 附加题解决方案: 207 | 208 | ```py 209 | # draggable rectangle with the animation blit techniques; see 210 | # http://www.scipy.org/Cookbook/Matplotlib/Animations 211 | import numpy as np 212 | import matplotlib.pyplot as plt 213 | 214 | class DraggableRectangle: 215 | lock = None # only one can be animated at a time 216 | def __init__(self, rect): 217 | self.rect = rect 218 | self.press = None 219 | self.background = None 220 | 221 | def connect(self): 222 | 'connect to all the events we need' 223 | self.cidpress = self.rect.figure.canvas.mpl_connect( 224 | 'button_press_event', self.on_press) 225 | self.cidrelease = self.rect.figure.canvas.mpl_connect( 226 | 'button_release_event', self.on_release) 227 | self.cidmotion = self.rect.figure.canvas.mpl_connect( 228 | 'motion_notify_event', self.on_motion) 229 | 230 | def on_press(self, event): 231 | 'on button press we will see if the mouse is over us and store some data' 232 | if event.inaxes != self.rect.axes: return 233 | if DraggableRectangle.lock is not None: return 234 | contains, attrd = self.rect.contains(event) 235 | if not contains: return 236 | print('event contains', self.rect.xy) 237 | x0, y0 = self.rect.xy 238 | self.press = x0, y0, event.xdata, event.ydata 239 | DraggableRectangle.lock = self 240 | 241 | # draw everything but the selected rectangle and store the pixel buffer 242 | canvas = self.rect.figure.canvas 243 | axes = self.rect.axes 244 | self.rect.set_animated(True) 245 | canvas.draw() 246 | self.background = canvas.copy_from_bbox(self.rect.axes.bbox) 247 | 248 | # now redraw just the rectangle 249 | axes.draw_artist(self.rect) 250 | 251 | # and blit just the redrawn area 252 | canvas.blit(axes.bbox) 253 | 254 | def on_motion(self, event): 255 | 'on motion we will move the rect if the mouse is over us' 256 | if DraggableRectangle.lock is not self: 257 | return 258 | if event.inaxes != self.rect.axes: return 259 | x0, y0, xpress, ypress = self.press 260 | dx = event.xdata - xpress 261 | dy = event.ydata - ypress 262 | self.rect.set_x(x0+dx) 263 | self.rect.set_y(y0+dy) 264 | 265 | canvas = self.rect.figure.canvas 266 | axes = self.rect.axes 267 | # restore the background region 268 | canvas.restore_region(self.background) 269 | 270 | # redraw just the current rectangle 271 | axes.draw_artist(self.rect) 272 | 273 | # blit just the redrawn area 274 | canvas.blit(axes.bbox) 275 | 276 | def on_release(self, event): 277 | 'on release we reset the press data' 278 | if DraggableRectangle.lock is not self: 279 | return 280 | 281 | self.press = None 282 | DraggableRectangle.lock = None 283 | 284 | # turn off the rect animation property and reset the background 285 | self.rect.set_animated(False) 286 | self.background = None 287 | 288 | # redraw the full figure 289 | self.rect.figure.canvas.draw() 290 | 291 | def disconnect(self): 292 | 'disconnect all the stored connection ids' 293 | self.rect.figure.canvas.mpl_disconnect(self.cidpress) 294 | self.rect.figure.canvas.mpl_disconnect(self.cidrelease) 295 | self.rect.figure.canvas.mpl_disconnect(self.cidmotion) 296 | 297 | fig = plt.figure() 298 | ax = fig.add_subplot(111) 299 | rects = ax.bar(range(10), 20*np.random.rand(10)) 300 | drs = [] 301 | for rect in rects: 302 | dr = DraggableRectangle(rect) 303 | dr.connect() 304 | drs.append(dr) 305 | 306 | plt.show() 307 | ``` 308 | 309 | ## 鼠标进入和离开 310 | 311 | 如果希望在鼠标进入或离开图形时通知你,你可以连接到图形/轴域进入/离开事件。 下面是一个简单的例子,它改变了鼠标所在的轴域和图形的背景颜色: 312 | 313 | ```py 314 | """ 315 | Illustrate the figure and axes enter and leave events by changing the 316 | frame colors on enter and leave 317 | """ 318 | import matplotlib.pyplot as plt 319 | 320 | def enter_axes(event): 321 | print('enter_axes', event.inaxes) 322 | event.inaxes.patch.set_facecolor('yellow') 323 | event.canvas.draw() 324 | 325 | def leave_axes(event): 326 | print('leave_axes', event.inaxes) 327 | event.inaxes.patch.set_facecolor('white') 328 | event.canvas.draw() 329 | 330 | def enter_figure(event): 331 | print('enter_figure', event.canvas.figure) 332 | event.canvas.figure.patch.set_facecolor('red') 333 | event.canvas.draw() 334 | 335 | def leave_figure(event): 336 | print('leave_figure', event.canvas.figure) 337 | event.canvas.figure.patch.set_facecolor('grey') 338 | event.canvas.draw() 339 | 340 | fig1 = plt.figure() 341 | fig1.suptitle('mouse hover over figure or axes to trigger events') 342 | ax1 = fig1.add_subplot(211) 343 | ax2 = fig1.add_subplot(212) 344 | 345 | fig1.canvas.mpl_connect('figure_enter_event', enter_figure) 346 | fig1.canvas.mpl_connect('figure_leave_event', leave_figure) 347 | fig1.canvas.mpl_connect('axes_enter_event', enter_axes) 348 | fig1.canvas.mpl_connect('axes_leave_event', leave_axes) 349 | 350 | fig2 = plt.figure() 351 | fig2.suptitle('mouse hover over figure or axes to trigger events') 352 | ax1 = fig2.add_subplot(211) 353 | ax2 = fig2.add_subplot(212) 354 | 355 | fig2.canvas.mpl_connect('figure_enter_event', enter_figure) 356 | fig2.canvas.mpl_connect('figure_leave_event', leave_figure) 357 | fig2.canvas.mpl_connect('axes_enter_event', enter_axes) 358 | fig2.canvas.mpl_connect('axes_leave_event', leave_axes) 359 | 360 | plt.show() 361 | ``` 362 | 363 | ## 对象拾取 364 | 365 | 你可以通过设置艺术家的`picker `属性(例如,matplotlib `Line2D`,`Text`,`Patch`,`Polygon`,`AxesImage`等)来启用选择, 366 | 367 | `picker `属性有多种含义: 368 | 369 | `None` 370 | 371 | 选择对于该艺术家已禁用(默认) 372 | 373 | `boolean` 374 | 375 | 如果为`True`,则启用选择,当鼠标移动到该艺术家上方时,会触发事件 376 | 377 | `float` 378 | 379 | 如果选择器是数字,则将其解释为点的 ε 公差,并且如果其数据在鼠标事件的 ε 内,则艺术家将触发事件。 对于像线条和补丁集合的一些艺术家,艺术家可以向生成的选择事件提供附加数据,例如,在选择事件的 ε 内的数据的索引。 380 | 381 | 函数 382 | 383 | 如果拾取器是可调用的,则它是用户提供的函数,用于确定艺术家是否被鼠标事件击中。 签名为`hit, props = picker(artist, mouseevent)`,用于测试是否命中。 如果鼠标事件在艺术家上,返回`hit = True`,`props`是一个属性字典,它们会添加到`PickEvent`属性。 384 | 385 | 通过设置`picker`属性启用对艺术家进行拾取后,你需要连接到图画布的`pick_event`,以便在鼠标按下事件中获取拾取回调。 例如: 386 | 387 | ```py 388 | def pick_handler(event): 389 | mouseevent = event.mouseevent 390 | artist = event.artist 391 | # now do something with this... 392 | ``` 393 | 394 | 传给你的回调的`PickEvent`事件永远有两个属性: 395 | 396 | `mouseevent ` 397 | 398 | 是生成拾取事件的鼠标事件。鼠标事件具有像`x`和`y`(显示空间中的坐标,例如,距离左,下的像素)和`xdata`,`ydata`(数据空间中的坐标)的属性。 此外,你可以获取有关按下哪些按钮,按下哪些键,鼠标在哪个轴域上面等信息。详细信息请参阅`matplotlib.backend_bases.MouseEvent`。 399 | 400 | `artist` 401 | 402 | 生成拾取事件的`Artist`。 403 | 404 | 另外,像`Line2D`和`PatchCollection`的某些艺术家可以将附加的元数据(如索引)附加到满足选择器标准的数据中(例如,行中在指定 ε 容差内的所有点) 405 | 406 | ### 简单拾取示例 407 | 408 | 409 | 在下面的示例中,我们将行选择器属性设置为标量,因此它表示以点为单位的容差(72 点/英寸)。 当拾取事件位于距离线条的容差范围时,将调用`onpick`回调函数,并且带有在拾取距离容差内的数据顶点索引。 我们的`onpick`回调函数只打印在拾取位置上的数据。 不同的 matplotlib 艺术家可以将不同的数据附加到`PickEvent`。 例如,`Line2D`将`ind`属性作为索引附加到拾取点下面的行数据中。 有关`Line`的`PickEvent`属性的详细信息,请参阅`pick()`。 这里是代码: 410 | 411 | ```py 412 | import numpy as np 413 | import matplotlib.pyplot as plt 414 | 415 | fig = plt.figure() 416 | ax = fig.add_subplot(111) 417 | ax.set_title('click on points') 418 | 419 | line, = ax.plot(np.random.rand(100), 'o', picker=5) # 5 points tolerance 420 | 421 | def onpick(event): 422 | thisline = event.artist 423 | xdata = thisline.get_xdata() 424 | ydata = thisline.get_ydata() 425 | ind = event.ind 426 | points = tuple(zip(xdata[ind], ydata[ind])) 427 | print('onpick points:', points) 428 | 429 | fig.canvas.mpl_connect('pick_event', onpick) 430 | 431 | plt.show() 432 | ``` 433 | 434 | ### 拾取练习 435 | 436 | 创建含有 100 个数组的数据集,包含 1000 个高斯随机数,并计算每个数组的样本平均值和标准差(提示:`numpy`数组具有`mean`和`std`方法),并制作 100 个均值与 100 个标准的`xy`标记图。 将绘图命令创建的线条连接到拾取事件,并绘制数据的原始时间序列,这些数据生成了被点击的点。 如果在被点击的点的容差范围内存在多于一个点,则可以使用多个子图来绘制多个时间序列。 437 | 438 | 练习的解决方案: 439 | 440 | ```py 441 | """ 442 | compute the mean and stddev of 100 data sets and plot mean vs stddev. 443 | When you click on one of the mu, sigma points, plot the raw data from 444 | the dataset that generated the mean and stddev 445 | """ 446 | import numpy as np 447 | import matplotlib.pyplot as plt 448 | 449 | X = np.random.rand(100, 1000) 450 | xs = np.mean(X, axis=1) 451 | ys = np.std(X, axis=1) 452 | 453 | fig = plt.figure() 454 | ax = fig.add_subplot(111) 455 | ax.set_title('click on point to plot time series') 456 | line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance 457 | 458 | 459 | def onpick(event): 460 | 461 | if event.artist!=line: return True 462 | 463 | N = len(event.ind) 464 | if not N: return True 465 | 466 | 467 | figi = plt.figure() 468 | for subplotnum, dataind in enumerate(event.ind): 469 | ax = figi.add_subplot(N,1,subplotnum+1) 470 | ax.plot(X[dataind]) 471 | ax.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]), 472 | transform=ax.transAxes, va='top') 473 | ax.set_ylim(-0.5, 1.5) 474 | figi.show() 475 | return True 476 | 477 | fig.canvas.mpl_connect('pick_event', onpick) 478 | 479 | plt.show() 480 | ``` 481 | -------------------------------------------------------------------------------- /7.md: -------------------------------------------------------------------------------- 1 | # 交互式绘图 -------------------------------------------------------------------------------- /8.1.md: -------------------------------------------------------------------------------- 1 | # 屏幕截图 2 | 3 | > 原文:[Screenshots](http://matplotlib.org/users/screenshots.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 这里你会找到一些示例图和生成它们的代码。 10 | 11 | ## 简单绘图 12 | 13 | 这里是一个带有文本标签的基本的绘图: 14 | 15 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/simple_plot.py) 16 | 17 | ![](http://matplotlib.org/_images/simple_plot1.png) 18 | 19 | ## 子图示例 20 | 21 | 多个轴域(例如子图)可使用`subplot()`命令创建: 22 | 23 | [源代码](http://matplotlib.org/mpl_examples/subplots_axes_and_figures/subplot_demo.py) 24 | 25 | ![](http://matplotlib.org/_images/subplot_demo3.png) 26 | 27 | ## 直方图 28 | 29 | `hist()`命令自动生成直方图,并返回项数或者概率: 30 | 31 | [源代码](http://matplotlib.org/mpl_examples/statistics/histogram_demo_features.py) 32 | 33 | ![](http://matplotlib.org/_images/histogram_demo_features2.png) 34 | 35 | ## 路径示例 36 | 37 | 你可以使用` matplotlib.path`模块,在`maplotlib`中添加任意路径: 38 | 39 | [源代码](http://matplotlib.org/mpl_examples/shapes_and_collections/path_patch_demo.py) 40 | 41 | ![](http://matplotlib.org/_images/path_patch_demo1.png) 42 | 43 | ## mplot3d 44 | 45 | mplot3d 工具包(见 [mplot3d 教程](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#toolkit-mplot3d-tutorial)和 [mplot3d 示例](http://matplotlib.org/examples/mplot3d/index.html#mplot3d-examples-index))支持简单的三维图形,包括平台、线框图、散点图和条形图。 46 | 47 | [源代码](http://matplotlib.org/mpl_examples/mplot3d/surface3d_demo.py) 48 | 49 | ![](http://matplotlib.org/_images/surface3d_demo4.png) 50 | 51 | 感谢 John Porter,Jonathan Taylor,Reinier Heeres 和 Ben Root 开发了 mplot3d 工具包。 此工具包包含于所有标准 matplotlib 安装中。 52 | 53 | ## Streamplot 54 | 55 | `streamplot()`函数绘制向量场的流线图。 除了简单地绘制流线之外,它还允许将流线的颜色和/或线宽映射到单独的参数,例如向量场的速度或局部密度。 56 | 57 | [源代码](http://matplotlib.org/mpl_examples/images_contours_and_fields/streamplot_demo_features.py) 58 | 59 | ![](http://matplotlib.org/_images/streamplot_demo_features_001.png) 60 | 61 | ![](http://matplotlib.org/_images/streamplot_demo_features_011.png) 62 | 63 | 这个特性完善了绘制向量场的`quiver()`函数。 感谢 Tom Flanagan 和 Tony You 添加`streamplot`函数。 64 | 65 | ## 椭圆 66 | 67 | 为了支持 [Phoenix Mars Mission](http://www.jpl.nasa.gov/news/phoenix/main.php)(使用 matplotlib 展示地面跟踪的航天器),Michael Droettboom 在 Charlie Moad 的工作基础上提供了非常精确的椭圆弧的 8-样条近似(见[`Arc`](http://matplotlib.org/api/patches_api.html#matplotlib.patches.Arc)),它对缩放级别并不敏感。 68 | 69 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/ellipse_demo.py) 70 | 71 | ![](http://matplotlib.org/_images/ellipse_demo1.png) 72 | 73 | ## 条形图 74 | 75 | 使用`bar()`命令创建条形图十分容易,其中包括一些定制(如误差条): 76 | 77 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/barchart_demo.py) 78 | 79 | ![](http://matplotlib.org/_images/barchart_demo3.png) 80 | 81 | 创建堆叠条([`bar_stacked.py`](http://matplotlib.org/examples/pylab_examples/bar_stacked.html)),蜡烛条([`finance_demo.py`](http://matplotlib.org/examples/pylab_examples/finance_demo.html))和水平条形图([`barh_demo.py`](http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html))也很简单。 82 | 83 | ## 饼图 84 | 85 | `pie()`命令允许您轻松创建饼图。 可选功能包括自动标记区域的百分比,从饼图中心向外生成一个或多个楔形以及阴影效果。 仔细查看附加的代码,它用几行代码来生成这个图像。 86 | 87 | [源代码](http://matplotlib.org/mpl_examples/pie_and_polar_charts/pie_demo_features.py) 88 | 89 | ![](http://matplotlib.org/_images/pie_demo_features_001.png) 90 | 91 | ![](http://matplotlib.org/_images/pie_demo_features_011.png) 92 | 93 | ## 表格示例 94 | 95 | `table()`命令向轴域添加文本表格。 96 | 97 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/table_demo.py) 98 | 99 | ![](http://matplotlib.org/_images/table_demo1.png) 100 | 101 | ## 散点图示例 102 | 103 | `scatter()`命令使用(可选的)大小和颜色参数创建散点图。 此示例描绘了 Google 股票价格的变化,标记的尺寸反映了交易量,并且颜色随时间变化。 这里,ALPHA 属性用于制作半透明圆形标记。 104 | 105 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/scatter_demo2.py) 106 | 107 | ![](http://matplotlib.org/_images/scatter_demo21.png) 108 | 109 | ## 滑块示例 110 | 111 | Matplotlib 拥有基本的 GUI 小部件,它们独立于您正在使用的图形用户界面,允许您编写 GUI 交叉图形和小部件。 请参阅[`matplotlib.widgets`](http://matplotlib.org/api/widgets_api.html#module-matplotlib.widgets)和[小部件示例](http://matplotlib.org/examples/widgets/index.html)。 112 | 113 | [源代码](http://matplotlib.org/mpl_examples/widgets/slider_demo.py) 114 | 115 | ![](http://matplotlib.org/_images/slider_demo.png) 116 | 117 | ## 填充示例 118 | 119 | `fill()`命令可以绘制填充曲线和多边形: 120 | 121 | 122 | [源代码](http://matplotlib.org/mpl_examples/lines_bars_and_markers/fill_demo.py) 123 | 124 | ![](http://matplotlib.org/_images/fill_demo2.png) 125 | 126 | 感谢 Andrew Straw 添加了这个函数。 127 | 128 | ## 日期示例 129 | 130 | 您可以绘制日期数据与主要和次要刻度,以及用于二者的自定义刻度格式化器。 131 | 132 | [源代码](http://matplotlib.org/mpl_examples/api/date_demo.py) 133 | 134 | ![](http://matplotlib.org/_images/date_demo3.png) 135 | 136 | 详细信息和用法请参阅[`matplotlib.ticker`](http://matplotlib.org/api/ticker_api.html#module-matplotlib.ticker)和[`matplotlib.dates`](http://matplotlib.org/api/dates_api.html#module-matplotlib.dates)。 137 | 138 | ## 金融图表 139 | 140 | 您可以通过结合 matplotlib 提供的各种绘图函数,布局命令和标签工具来创建复杂的金融图表。 以下示例模拟 ChartDirector 中的一个财务图: 141 | 142 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/finance_work2.py) 143 | 144 | ![](http://matplotlib.org/_images/finance_work21.png) 145 | 146 | ## 地图示例 147 | 148 | Jeff Whitaker 的 [Basemap](http://matplotlib.org/mpl_toolkits/index.html#toolkit-basemap) 附加工具包可以在许多不同的地图投影上绘制数据。 此示例展示了如何在直角投影上绘制轮廓,标记和文本,以 NASA 的“蓝色大理石”卫星图像作为背景。 149 | 150 | [源代码](http://matplotlib.org/pyplots/plotmap.py) 151 | 152 | ## 对数绘图 153 | 154 | `semilogx()`,`semilogy()`和`loglog()`函数简化了对数绘图的创建。 155 | 156 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/log_demo.py) 157 | 158 | ![](http://matplotlib.org/_images/log_demo2.png) 159 | 160 | ## 极轴绘图 161 | 162 | `polar()`命令生成极轴绘图。 163 | 164 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/polar_demo.py) 165 | 166 | ![](http://matplotlib.org/_images/polar_demo1.png) 167 | 168 | ## 图例 169 | 170 | `legend()`命令使用 MATLAB 兼容的图例布局命令自动生成图形图例。 171 | 172 | [源代码](http://matplotlib.org/mpl_examples/api/legend_demo.py) 173 | 174 | ![](http://matplotlib.org/_images/legend_demo6.png) 175 | 176 | 感谢 Charles Twardy 编写了图例命令的输入。 177 | 178 | ## 数学公式示例 179 | 180 | 下面是 matplotlib 内部数学公式引擎现在支持的许多 TeX 表达式的示例。 `mathtext`模块使用 [freetype2](http://www.freetype.org/) 和 BaKoMa 或 [STIX](http://www.stixfonts.org/) 现代字体提供 TeX 风格的数学表达式。 其他详细信息请参阅[`matplotlib.mathtext`](http://matplotlib.org/api/mathtext_api.html#module-matplotlib.mathtext)模块。 181 | 182 | [源代码](http://matplotlib.org/mpl_examples/pylab_examples/mathtext_examples.py) 183 | 184 | ![](http://matplotlib.org/_images/mathtext_examples_01_001.png) 185 | 186 | Matplotlib 的`mathtext`基础结构是一个独立的实现,不需要 TeX 或计算机上安装的任何外部软件包。 请参阅[编写数学表达式](http://matplotlib.org/users/mathtext.html#mathtext-tutorial)教程。 187 | 188 | ## TeX 原生渲染 189 | 190 | 虽然 matplotlib 的内部数学渲染引擎相当强大,但有时你还是需要 TeX。Matplotlib 支持带有 usetex 选项的 TeX 外部字符串渲染。 191 | 192 | [源代码](http://matplotlib.org/pyplots/tex_demo.py) 193 | 194 | ![](http://matplotlib.org/_images/tex_demo1.png) 195 | 196 | ## EEG 示例 197 | 198 | 您可以将 matplotlib 嵌入到 pygtk,wx,Tk,FLTK 或 Qt 应用程序中。 这是一个名为 [pbrain](http://github.com/nipy/pbrain) 的 EEG 查看器的屏幕截图。 199 | 200 | ![](http://matplotlib.org/_images/eeg_small.png) 201 | 202 | 下轴使用`specgram()`绘制其中一个 EEG 通道的频谱图。 203 | 204 | 有关将 matplotlib 嵌入不同工具包的示例,请参阅: 205 | 206 | + [`user_interfaces`示例代码:`embedding_in_gtk2.py`](http://matplotlib.org/examples/user_interfaces/embedding_in_gtk2.html#user-interfaces-embedding-in-gtk2) 207 | + [`user_interfaces`示例代码:`embedding_in_wx2.py`](http://matplotlib.org/examples/user_interfaces/embedding_in_wx2.html#user-interfaces-embedding-in-wx2) 208 | + [`user_interfaces`示例代码:`mpl_with_glade.py`](http://matplotlib.org/examples/user_interfaces/mpl_with_glade.html#user-interfaces-mpl-with-glade) 209 | + [`user_interfaces`示例代码:`embedding_in_qt4.py`](http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html#user-interfaces-embedding-in-qt4) 210 | + [`user_interfaces`示例代码:`embedding_in_tk.py`](http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html#user-interfaces-embedding-in-tk) 211 | 212 | ## XKCD 风格的手绘图 213 | 214 | matplotlib 支持`xkcd`风格的绘图。 215 | 216 | [源代码](http://matplotlib.org/mpl_examples/showcase/xkcd.py) 217 | 218 | ![](http://matplotlib.org/_images/xkcd_001.png) 219 | 220 | ![](http://matplotlib.org/_images/xkcd_011.png) 221 | -------------------------------------------------------------------------------- /8.2.md: -------------------------------------------------------------------------------- 1 | # 我们最喜欢的秘籍 2 | 3 | > 原文:[Our Favorite Recipes](http://matplotlib.org/users/recipes.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | 这里是一个简短的教程,示例和代码片段的集合,展示了一些有用的经验和技巧,来制作更精美的图像,并克服一些 matplotlib 的缺陷。 10 | 11 | ## 共享轴限制和视图 12 | 13 | 通常用于使两个或更多绘图共享一个轴,例如,两个子绘图具有时间作为公共轴。 当你平移和缩放一个绘图,你想让另一个绘图一起移动。 为了方便这一点,matplotlib 轴支持`sharex`和`sharey`属性。 创建`subplot()`或`axes()`实例时,你可以传入一个关键字,表明要共享的轴。 14 | 15 | ```py 16 | In [96]: t = np.arange(0, 10, 0.01) 17 | 18 | In [97]: ax1 = plt.subplot(211) 19 | 20 | In [98]: ax1.plot(t, np.sin(2*np.pi*t)) 21 | Out[98]: [] 22 | 23 | In [99]: ax2 = plt.subplot(212, sharex=ax1) 24 | 25 | In [100]: ax2.plot(t, np.sin(4*np.pi*t)) 26 | Out[100]: [] 27 | ``` 28 | 29 | ## 轻松创建子图 30 | 31 | 在 matplotlib 的早期版本中,如果你想使用 pythonic API 并创建一个`figure`实例,并从中创建一个`subplots`网格,而且可能带有共享轴,它涉及大量的样板代码。 例如: 32 | 33 | ```py 34 | # old style 35 | fig = plt.figure() 36 | ax1 = fig.add_subplot(221) 37 | ax2 = fig.add_subplot(222, sharex=ax1, sharey=ax1) 38 | ax3 = fig.add_subplot(223, sharex=ax1, sharey=ax1) 39 | ax3 = fig.add_subplot(224, sharex=ax1, sharey=ax1) 40 | ``` 41 | 42 | 43 | Fernando Perez 提供了一个很好的顶级方法,来一次性创建`subplots()`(注意末尾的`s`),并为所有子图开启`x`和`y`共享。 你可以单独解构来获取轴域: 44 | 45 | ```py 46 | # new style method 1; unpack the axes 47 | fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True) 48 | ax1.plot(x) 49 | ``` 50 | 51 | 或将它们作为行数乘列数的对象数组返回,支持 numpy 索引: 52 | 53 | ```py 54 | # new style method 2; use an axes array 55 | fig, axs = plt.subplots(2, 2, sharex=True, sharey=True) 56 | axs[0,0].plot(x) 57 | ``` 58 | 59 | ## 修复常见的日期问题 60 | 61 | matplotlib 允许你本地绘制 python datetime 实例,并且在大多数情况下,可以很好地挑选刻度位置和字符串格式。 但有几件事情它不能妥善处理,这里有一些技巧,用于帮助你解决他们。 我们将在`numpy`记录数组中加载一些包含`datetime.date`对象的示例日期数据: 62 | 63 | ```py 64 | In [63]: datafile = cbook.get_sample_data('goog.npy') 65 | 66 | In [64]: r = np.load(datafile).view(np.recarray) 67 | 68 | In [65]: r.dtype 69 | Out[65]: dtype([('date', '|O4'), ('', '|V4'), ('open', '] 86 | ``` 87 | 88 | 你会看到 x 轴标签重合到一起。 89 | 90 | ![](http://matplotlib.org/_images/recipes-2.png) 91 | 92 | 另一个麻烦是,如果你将鼠标悬停在窗口上,并在 x 和 y 坐标处查看 matplotlib 工具栏([交互式导航](http://matplotlib.org/users/navigation_toolbar.html#navigation-toolbar))的右下角,你会看到 x 位置的格式与刻度标签的格式相同, 例如,『Dec 2004』。 我们想要的是工具栏中的位置具有更高的精确度,例如,鼠标悬停在上面时给我们确切的日期。 为了解决第一个问题,我们可以使用[`matplotlib.figure.Figure.autofmt_xdate()`](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.autofmt_xdate)。修复第二个问题,我们可以使用`ax.fmt_xdata`属性,该属性可以设置为任何接受标量并返回字符串的函数。 matplotlib 有一些内置的日期格式化器,所以我们将使用其中的一个。 93 | 94 | ```py 95 | plt.close('all') 96 | fig, ax = plt.subplots(1) 97 | ax.plot(r.date, r.close) 98 | 99 | # rotate and align the tick labels so they look better 100 | fig.autofmt_xdate() 101 | 102 | # use a more precise date string for the x axis locations in the 103 | # toolbar 104 | import matplotlib.dates as mdates 105 | ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') 106 | plt.title('fig.autofmt_xdate fixes the labels') 107 | ``` 108 | 109 | ![](http://matplotlib.org/_images/recipes-3.png) 110 | 111 | 现在,当你将鼠标悬停在绘制的数据上,你将在工具栏中看到如`2004-12-01`的日期格式字符串。 112 | 113 | ## 透明度填充 114 | 115 | `fill_between()`函数在最小和最大边界之间生成阴影区域,用于展示范围。 它有一个非常方便的参数,将填充范围与逻辑范围组合,例如,以便仅填充超过某个阈值的曲线。= 116 | 117 | 基本上,`fill_between`可以用来增强图形的视觉外观。 让我们比较两个财务-时间图表,左边是一个简单的线框图,右边是一个填充图。 118 | 119 | ![](http://matplotlib.org/_images/recipes-4.png) 120 | 121 | Alpha 通道在这里不是必需的,但它可以用来软化颜色,创建更具视觉吸引力的绘图。 在其他示例中,我们将在下面看到,Alpha 通道在功能上有用,因为阴影区域可以重叠,Alpha 允许你同时看到两者。 注意,postscript 格式不支持 alpha(这是一个 postscript 限制,而不是一个 matplotlib 限制),因此,当使用 alpha 时,将你的数字保存在 PNG,PDF 或 SVG 中。 122 | 123 | 我们的下一个例子是计算随机漫步的两个群体,它们具有不同的正态分布平均值和标准差,足迹会从中绘制。我们使用共享区域来绘制群体的平均位置的加/减一个标准差。 这里的 Alpha 通道是有用的,不只是为了审美。 124 | 125 | ```py 126 | import matplotlib.pyplot as plt 127 | import numpy as np 128 | 129 | Nsteps, Nwalkers = 100, 250 130 | t = np.arange(Nsteps) 131 | 132 | # an (Nsteps x Nwalkers) array of random walk steps 133 | S1 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers) 134 | S2 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers) 135 | 136 | # an (Nsteps x Nwalkers) array of random walker positions 137 | X1 = S1.cumsum(axis=0) 138 | X2 = S2.cumsum(axis=0) 139 | 140 | 141 | # Nsteps length arrays empirical means and standard deviations of both 142 | # populations over time 143 | mu1 = X1.mean(axis=1) 144 | sigma1 = X1.std(axis=1) 145 | mu2 = X2.mean(axis=1) 146 | sigma2 = X2.std(axis=1) 147 | 148 | # plot it! 149 | fig, ax = plt.subplots(1) 150 | ax.plot(t, mu1, lw=2, label='mean population 1', color='blue') 151 | ax.plot(t, mu2, lw=2, label='mean population 2', color='yellow') 152 | ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='blue', alpha=0.5) 153 | ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='yellow', alpha=0.5) 154 | ax.set_title('random walkers empirical $\mu$ and $\pm \sigma$ interval') 155 | ax.legend(loc='upper left') 156 | ax.set_xlabel('num steps') 157 | ax.set_ylabel('position') 158 | ax.grid() 159 | ``` 160 | 161 | ![](http://matplotlib.org/_images/recipes-5.png) 162 | 163 | `where`关键字参数非常方便地用于突出显示图形的某些区域。 其中使用与`x`,`ymin`和`ymax`参数相同长度的布尔掩码,并且只填充布尔掩码为`True`的区域。 在下面的例子中,我们模拟一个随机漫步者,并计算人口位置的分析平均值和标准差。 群体平均值显示为黑色虚线,并且平均值的加/减一个标准差显示为黄色填充区域。 我们使用`where=X>upper_bound`找到漫步者在一个标准差边界之上的区域,并将该区域变成蓝色。 164 | 165 | ![](http://matplotlib.org/_images/recipes-6.png) 166 | 167 | ## 透明、花式图例 168 | 169 | 有时你在绘制数据之前就知道你的数据是什么样的,并且可能知道例如右上角没有太多数据。 然后,你可以安全地创建不覆盖你的数据的图例: 170 | 171 | ```py 172 | ax.legend(loc='upper right') 173 | ``` 174 | 175 | 其他时候你不知道你的数据在哪里,而`loc ='best'`将尝试和放置图例: 176 | 177 | ```py 178 | ax.legend(loc='best') 179 | ``` 180 | 181 | 但仍然,你的图例可能会覆盖你的数据,在这些情况下,使图例框架透明非常不错。 182 | 183 | ```py 184 | np.random.seed(1234) 185 | fig, ax = plt.subplots(1) 186 | ax.plot(np.random.randn(300), 'o-', label='normal distribution') 187 | ax.plot(np.random.rand(300), 's-', label='uniform distribution') 188 | ax.set_ylim(-3, 3) 189 | ax.legend(loc='best', fancybox=True, framealpha=0.5) 190 | 191 | ax.set_title('fancy, transparent legends') 192 | ``` 193 | 194 | ![](http://matplotlib.org/_images/recipes-7.png) 195 | 196 | ## 放置文本框 197 | 198 | 当使用文本框装饰轴时,两个有用的技巧是将文本放置在轴域坐标中(请参见[变换教程](http://matplotlib.org/users/transforms_tutorial.html#transforms-tutorial)),因此文本不会随着 x 或 y 轴的变化而移动。 你还可以使用文本的`bbox`属性,用`Patch`实例包围文本 - `bbox`关键字参数接受字典,字典的键是补丁的属性。 199 | 200 | ```py 201 | np.random.seed(1234) 202 | fig, ax = plt.subplots(1) 203 | x = 30*np.random.randn(10000) 204 | mu = x.mean() 205 | median = np.median(x) 206 | sigma = x.std() 207 | textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma) 208 | 209 | ax.hist(x, 50) 210 | # these are matplotlib.patch.Patch properties 211 | props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) 212 | 213 | # place a text box in upper left in axes coords 214 | ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14, 215 | verticalalignment='top', bbox=props) 216 | ``` 217 | 218 | ![](http://matplotlib.org/_images/recipes-8.png) 219 | -------------------------------------------------------------------------------- /8.md: -------------------------------------------------------------------------------- 1 | # 所选示例 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Matplotlib 用户指南 2 | 3 | > 来源:[User's Guide](http://matplotlib.org/users/index.html) 4 | 5 | > 译者:[飞龙](https://github.com/) 6 | 7 | > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 8 | 9 | + [在线阅读](https://www.gitbook.com/book/wizardforcel/matplotlib-user-guide/details) 10 | + [PDF格式](https://www.gitbook.com/download/pdf/book/wizardforcel/matplotlib-user-guide) 11 | + [EPUB格式](https://www.gitbook.com/download/epub/book/wizardforcel/matplotlib-user-guide) 12 | + [MOBI格式](https://www.gitbook.com/download/mobi/book/wizardforcel/matplotlib-user-guide) 13 | + [代码仓库](https://github.com/wizardforcel/matplotlib-user-guide-zh) 14 | 15 | ## 赞助我 16 | 17 | ![](http://upload-images.jianshu.io/upload_images/118142-fe132ca3591a3d52.png) -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | + [Matplotlib 用户指南](README.md) 2 | + [简介](1.md) 3 | + [安装](2.md) 4 | + [教程](3.md) 5 | + [Pyplot 教程](3.1.md) 6 | + [图像教程](3.2.md) 7 | + [使用 GridSpec 自定义子图位置](3.3.md) 8 | + [密致布局教程](3.4.md) 9 | + [艺术家教程](3.5.md) 10 | + [图例指南](3.6.md) 11 | + [变换教程](3.7.md) 12 | + [路径教程](3.8.md) 13 | + [路径效果指南](3.9.md) 14 | + [处理文本](4.md) 15 | + [引言](4.1.md) 16 | + [基本的文本命令](4.2.md) 17 | + [文本属性及布局](4.3.md) 18 | + [默认字体](4.4.md) 19 | + [标注](4.5.md) 20 | + [编写数学表达式](4.6.md) 21 | + [使用 LaTeX 渲染文本](4.7.md) 22 | + [XeLaTeX/LuaLaTeX 设置](4.8.md) 23 | + [颜色](5.md) 24 | + [指定颜色](5.1.md) 25 | + [选择颜色表](5.2.md) 26 | + [颜色表标准化](5.3.md) 27 | + [自定义 matplotlib](6.md) 28 | + [交互式绘图](7.md) 29 | + [交互式导航](7.1.md) 30 | + [在 Python Shell 中使用 matplotlib](7.2.md) 31 | + [事件处理及拾取](7.3.md) 32 | + [所选示例](8.md) 33 | + [屏幕截图](8.1.md) 34 | + [我们最喜欢的秘籍](8.2.md) 35 | + [术语表](glossary.md) 36 | -------------------------------------------------------------------------------- /glossary.md: -------------------------------------------------------------------------------- 1 | # 术语表 2 | 3 | | 英文 | 中文 | 4 | | --- | --- | 5 | | Annotation | 标注 | 6 | | Artist | 艺术家 | 7 | | Axes | 轴域 | 8 | | Axis | 轴/坐标轴 | 9 | | Bézier | 贝塞尔 | 10 | | Coordinate | 坐标 | 11 | | Coordinate System | 坐标系 | 12 | | Figure | 图形 | 13 | | Handle | 句柄 | 14 | | Handler | 处理器 | 15 | | Image | 图像 | 16 | | Legend | 图例 | 17 | | Line | 线条 | 18 | | Patch | 补丁 | 19 | | Path | 路径 | 20 | | Pick | 拾取 | 21 | | Subplot | 子图 | 22 | | Text | 文本 | 23 | | Tick | 刻度 | 24 | | Tick Label | 刻度标签 | 25 | | Transformation | 变换 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /styles/ebook.css: -------------------------------------------------------------------------------- 1 | /* GitHub stylesheet for MarkdownPad (http://markdownpad.com) */ 2 | /* Author: Nicolas Hery - http://nicolashery.com */ 3 | /* Version: b13fe65ca28d2e568c6ed5d7f06581183df8f2ff */ 4 | /* Source: https://github.com/nicolahery/markdownpad-github */ 5 | 6 | /* RESET 7 | =============================================================================*/ 8 | 9 | html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { 10 | margin: 0; 11 | padding: 0; 12 | border: 0; 13 | } 14 | 15 | /* BODY 16 | =============================================================================*/ 17 | 18 | body { 19 | font-family: Helvetica, arial, freesans, clean, sans-serif; 20 | font-size: 14px; 21 | line-height: 1.6; 22 | color: #333; 23 | background-color: #fff; 24 | padding: 20px; 25 | max-width: 960px; 26 | margin: 0 auto; 27 | } 28 | 29 | body>*:first-child { 30 | margin-top: 0 !important; 31 | } 32 | 33 | body>*:last-child { 34 | margin-bottom: 0 !important; 35 | } 36 | 37 | /* BLOCKS 38 | =============================================================================*/ 39 | 40 | p, blockquote, ul, ol, dl, table, pre { 41 | margin: 15px 0; 42 | } 43 | 44 | /* HEADERS 45 | =============================================================================*/ 46 | 47 | h1, h2, h3, h4, h5, h6 { 48 | margin: 20px 0 10px; 49 | padding: 0; 50 | font-weight: bold; 51 | -webkit-font-smoothing: antialiased; 52 | } 53 | 54 | h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code { 55 | font-size: inherit; 56 | } 57 | 58 | h1 { 59 | font-size: 24px; 60 | border-bottom: 1px solid #ccc; 61 | color: #000; 62 | } 63 | 64 | h2 { 65 | font-size: 18px; 66 | color: #000; 67 | } 68 | 69 | h3 { 70 | font-size: 14px; 71 | } 72 | 73 | h4 { 74 | font-size: 14px; 75 | } 76 | 77 | h5 { 78 | font-size: 14px; 79 | } 80 | 81 | h6 { 82 | color: #777; 83 | font-size: 14px; 84 | } 85 | 86 | body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child { 87 | margin-top: 0; 88 | padding-top: 0; 89 | } 90 | 91 | a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 { 92 | margin-top: 0; 93 | padding-top: 0; 94 | } 95 | 96 | h1+p, h2+p, h3+p, h4+p, h5+p, h6+p { 97 | margin-top: 10px; 98 | } 99 | 100 | /* LINKS 101 | =============================================================================*/ 102 | 103 | a { 104 | color: #4183C4; 105 | text-decoration: none; 106 | } 107 | 108 | a:hover { 109 | text-decoration: underline; 110 | } 111 | 112 | /* LISTS 113 | =============================================================================*/ 114 | 115 | ul, ol { 116 | padding-left: 30px; 117 | } 118 | 119 | ul li > :first-child, 120 | ol li > :first-child, 121 | ul li ul:first-of-type, 122 | ol li ol:first-of-type, 123 | ul li ol:first-of-type, 124 | ol li ul:first-of-type { 125 | margin-top: 0px; 126 | } 127 | 128 | ul ul, ul ol, ol ol, ol ul { 129 | margin-bottom: 0; 130 | } 131 | 132 | dl { 133 | padding: 0; 134 | } 135 | 136 | dl dt { 137 | font-size: 14px; 138 | font-weight: bold; 139 | font-style: italic; 140 | padding: 0; 141 | margin: 15px 0 5px; 142 | } 143 | 144 | dl dt:first-child { 145 | padding: 0; 146 | } 147 | 148 | dl dt>:first-child { 149 | margin-top: 0px; 150 | } 151 | 152 | dl dt>:last-child { 153 | margin-bottom: 0px; 154 | } 155 | 156 | dl dd { 157 | margin: 0 0 15px; 158 | padding: 0 15px; 159 | } 160 | 161 | dl dd>:first-child { 162 | margin-top: 0px; 163 | } 164 | 165 | dl dd>:last-child { 166 | margin-bottom: 0px; 167 | } 168 | 169 | /* CODE 170 | =============================================================================*/ 171 | 172 | pre, code, tt { 173 | font-size: 12px; 174 | font-family: Consolas, "Liberation Mono", Courier, monospace; 175 | } 176 | 177 | code, tt { 178 | margin: 0 0px; 179 | padding: 0px 0px; 180 | white-space: nowrap; 181 | border: 1px solid #eaeaea; 182 | background-color: #f8f8f8; 183 | border-radius: 3px; 184 | } 185 | 186 | pre>code { 187 | margin: 0; 188 | padding: 0; 189 | white-space: pre; 190 | border: none; 191 | background: transparent; 192 | } 193 | 194 | pre { 195 | background-color: #f8f8f8; 196 | border: 1px solid #ccc; 197 | font-size: 13px; 198 | line-height: 19px; 199 | overflow: auto; 200 | padding: 6px 10px; 201 | border-radius: 3px; 202 | } 203 | 204 | pre code, pre tt { 205 | background-color: transparent; 206 | border: none; 207 | } 208 | 209 | kbd { 210 | -moz-border-bottom-colors: none; 211 | -moz-border-left-colors: none; 212 | -moz-border-right-colors: none; 213 | -moz-border-top-colors: none; 214 | background-color: #DDDDDD; 215 | background-image: linear-gradient(#F1F1F1, #DDDDDD); 216 | background-repeat: repeat-x; 217 | border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; 218 | border-image: none; 219 | border-radius: 2px 2px 2px 2px; 220 | border-style: solid; 221 | border-width: 1px; 222 | font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; 223 | line-height: 10px; 224 | padding: 1px 4px; 225 | } 226 | 227 | /* QUOTES 228 | =============================================================================*/ 229 | 230 | blockquote { 231 | border-left: 4px solid #DDD; 232 | padding: 0 15px; 233 | color: #777; 234 | } 235 | 236 | blockquote>:first-child { 237 | margin-top: 0px; 238 | } 239 | 240 | blockquote>:last-child { 241 | margin-bottom: 0px; 242 | } 243 | 244 | /* HORIZONTAL RULES 245 | =============================================================================*/ 246 | 247 | hr { 248 | clear: both; 249 | margin: 15px 0; 250 | height: 0px; 251 | overflow: hidden; 252 | border: none; 253 | background: transparent; 254 | border-bottom: 4px solid #ddd; 255 | padding: 0; 256 | } 257 | 258 | /* TABLES 259 | =============================================================================*/ 260 | 261 | table th { 262 | font-weight: bold; 263 | } 264 | 265 | table th, table td { 266 | border: 1px solid #ccc; 267 | padding: 6px 13px; 268 | } 269 | 270 | table tr { 271 | border-top: 1px solid #ccc; 272 | background-color: #fff; 273 | } 274 | 275 | table tr:nth-child(2n) { 276 | background-color: #f8f8f8; 277 | } 278 | 279 | /* IMAGES 280 | =============================================================================*/ 281 | 282 | img { 283 | max-width: 100% 284 | } --------------------------------------------------------------------------------