├── .gitignore ├── .nojekyll ├── 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 ├── 404.html ├── 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 ├── CNAME ├── Dockerfile ├── LICENSE ├── README.md ├── SUMMARY.md ├── asset ├── docsify-apachecn-footer.js ├── docsify-baidu-push.js ├── docsify-baidu-stat.js ├── docsify-clicker.js ├── docsify-cnzz.js ├── docsify-copy-code.min.js ├── docsify.min.js ├── prism-darcula.css ├── prism-python.min.js ├── search.min.js ├── style.css └── vue.css ├── glossary.md ├── index.html ├── styles └── ebook.css └── update.sh /.gitignore: -------------------------------------------------------------------------------- 1 | _book 2 | -------------------------------------------------------------------------------- /.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/matplotlib-doc-zh/d82ca380b42e4bcb8f5a5fc3e87683fd7b635749/.nojekyll -------------------------------------------------------------------------------- /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.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 | # 文本处理 -------------------------------------------------------------------------------- /404.html: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: /404.html 3 | --- 4 | 5 | -------------------------------------------------------------------------------- /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/apachecn/matplotlib-doc-zh/d82ca380b42e4bcb8f5a5fc3e87683fd7b635749/5.2.md -------------------------------------------------------------------------------- /5.3.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apachecn/matplotlib-doc-zh/d82ca380b42e4bcb8f5a5fc3e87683fd7b635749/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 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | mpl.apachecn.org -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM httpd:2.4 2 | COPY ./ /usr/local/apache2/htdocs/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License (CC BY-NC-SA 4.0) 2 | 3 | Copyright © 2020 ApacheCN(apachecn@163.com) 4 | 5 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 6 | 7 | Section 1 – Definitions. 8 | 9 | a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 10 | b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 11 | c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. 12 | d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 13 | e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 14 | f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 15 | g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. 16 | h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 17 | i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 18 | j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. 19 | k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 20 | l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 21 | m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 22 | n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 23 | 24 | Section 2 – Scope. 25 | 26 | a. License grant. 27 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 28 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 29 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 30 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 31 | 3. Term. The term of this Public License is specified in Section 6(a). 32 | 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 33 | 5. Downstream recipients. 34 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 35 | B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. 36 | C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 37 | 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 38 | b. Other rights. 39 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 40 | 2. Patent and trademark rights are not licensed under this Public License. 41 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 42 | 43 | Section 3 – License Conditions. 44 | 45 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 46 | 47 | a. Attribution. 48 | 1. If You Share the Licensed Material (including in modified form), You must: 49 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 50 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 51 | ii. a copyright notice; 52 | iii. a notice that refers to this Public License; 53 | iv. a notice that refers to the disclaimer of warranties; 54 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 55 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 56 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 57 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 58 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 59 | b. ShareAlike. 60 | In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 61 | 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. 62 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 63 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 64 | 65 | Section 4 – Sui Generis Database Rights. 66 | 67 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 68 | 69 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 70 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 71 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 72 | 73 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 74 | 75 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 76 | 77 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 78 | b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 79 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 80 | 81 | Section 6 – Term and Termination. 82 | 83 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 84 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 85 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 86 | 2. upon express reinstatement by the Licensor. 87 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 88 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 89 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 90 | 91 | Section 7 – Other Terms and Conditions. 92 | 93 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 94 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 95 | 96 | Section 8 – Interpretation. 97 | 98 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 99 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 100 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 101 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. -------------------------------------------------------------------------------- /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://mpl.apachecn.org) 10 | + [在线阅读(Gitee)](https://apachecn.gitee.io/matplotlib-doc-zh/) 11 | + [PDF格式](https://www.gitbook.com/download/pdf/book/wizardforcel/matplotlib-user-guide) 12 | + [EPUB格式](https://www.gitbook.com/download/epub/book/wizardforcel/matplotlib-user-guide) 13 | + [MOBI格式](https://www.gitbook.com/download/mobi/book/wizardforcel/matplotlib-user-guide) 14 | + [代码仓库](https://github.com/wizardforcel/matplotlib-user-guide-zh) 15 | 16 | ## 下载 17 | 18 | ### Docker 19 | 20 | ``` 21 | docker pull apachecn0/matplotlib-doc-zh 22 | docker run -tid -p :80 apachecn0/matplotlib-doc-zh 23 | # 访问 http://localhost:{port} 查看文档 24 | ``` 25 | 26 | ### PYPI 27 | 28 | ``` 29 | pip install matplotlib-doc-zh 30 | matplotlib-doc-zh 31 | # 访问 http://localhost:{port} 查看文档 32 | ``` 33 | 34 | ### NPM 35 | 36 | ``` 37 | npm install -g matplotlib-doc-zh 38 | matplotlib-doc-zh 39 | # 访问 http://localhost:{port} 查看文档 40 | ``` 41 | 42 | ## 赞助我 43 | 44 | ![](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 | -------------------------------------------------------------------------------- /asset/docsify-apachecn-footer.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var footer = [ 3 | '
', 4 | '
', 5 | '

我们一直在努力

', 6 | '

apachecn/matplotlib-doc-zh

', 7 | '

', 8 | ' ', 9 | ' ', 10 | ' ML | ApacheCN

', 11 | '

', 12 | '
', 13 | ' ', 17 | '
', 18 | '
' 19 | ].join('\n') 20 | var plugin = function(hook) { 21 | hook.afterEach(function(html) { 22 | return html + footer 23 | }) 24 | hook.doneEach(function() { 25 | (adsbygoogle = window.adsbygoogle || []).push({}) 26 | }) 27 | } 28 | var plugins = window.$docsify.plugins || [] 29 | plugins.push(plugin) 30 | window.$docsify.plugins = plugins 31 | })() -------------------------------------------------------------------------------- /asset/docsify-baidu-push.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var plugin = function(hook) { 3 | hook.doneEach(function() { 4 | new Image().src = 5 | '//api.share.baidu.com/s.gif?r=' + 6 | encodeURIComponent(document.referrer) + 7 | "&l=" + encodeURIComponent(location.href) 8 | }) 9 | } 10 | var plugins = window.$docsify.plugins || [] 11 | plugins.push(plugin) 12 | window.$docsify.plugins = plugins 13 | })() -------------------------------------------------------------------------------- /asset/docsify-baidu-stat.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var plugin = function(hook) { 3 | hook.doneEach(function() { 4 | window._hmt = window._hmt || [] 5 | var hm = document.createElement("script") 6 | hm.src = "https://hm.baidu.com/hm.js?" + window.$docsify.bdStatId 7 | document.querySelector("article").appendChild(hm) 8 | }) 9 | } 10 | var plugins = window.$docsify.plugins || [] 11 | plugins.push(plugin) 12 | window.$docsify.plugins = plugins 13 | })() -------------------------------------------------------------------------------- /asset/docsify-clicker.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var ids = [ 3 | '109577065', '108852955', '102682374', '100520874', '92400861', '90312982', 4 | '109963325', '109323014', '109301511', '108898970', '108590722', '108538676', 5 | '108503526', '108437109', '108402202', '108292691', '108291153', '108268498', 6 | '108030854', '107867070', '107847299', '107827334', '107825454', '107802131', 7 | '107775320', '107752974', '107735139', '107702571', '107598864', '107584507', 8 | '107568311', '107526159', '107452391', '107437455', '107430050', '107395781', 9 | '107325304', '107283210', '107107145', '107085440', '106995421', '106993460', 10 | '106972215', '106959775', '106766787', '106749609', '106745967', '106634313', 11 | '106451602', '106180097', '106095505', '106077010', '106008089', '106002346', 12 | '105653809', '105647855', '105130705', '104837872', '104706815', '104192620', 13 | '104074941', '104040537', '103962171', '103793502', '103783460', '103774572', 14 | '103547748', '103547703', '103547571', '103490757', '103413481', '103341935', 15 | '103330191', '103246597', '103235808', '103204403', '103075981', '103015105', 16 | '103014899', '103014785', '103014702', '103014540', '102993780', '102993754', 17 | '102993680', '102958443', '102913317', '102903382', '102874766', '102870470', 18 | '102864513', '102811179', '102761237', '102711565', '102645443', '102621845', 19 | '102596167', '102593333', '102585262', '102558427', '102537547', '102530610', 20 | '102527017', '102504698', '102489806', '102372981', '102258897', '102257303', 21 | '102056248', '101920097', '101648638', '101516708', '101350577', '101268149', 22 | '101128167', '101107328', '101053939', '101038866', '100977414', '100945061', 23 | '100932401', '100886407', '100797378', '100634918', '100588305', '100572447', 24 | '100192249', '100153559', '100099032', '100061455', '100035392', '100033450', 25 | '99671267', '99624846', '99172551', '98992150', '98989508', '98987516', '98938304', 26 | '98937682', '98725145', '98521688', '98450861', '98306787', '98203342', '98026348', 27 | '97680167', '97492426', '97108940', '96888872', '96568559', '96509100', '96508938', 28 | '96508611', '96508374', '96498314', '96476494', '96333593', '96101522', '95989273', 29 | '95960507', '95771870', '95770611', '95766810', '95727700', '95588929', '95218707', 30 | '95073151', '95054615', '95016540', '94868371', '94839549', '94719281', '94401578', 31 | '93931439', '93853494', '93198026', '92397889', '92063437', '91635930', '91433989', 32 | '91128193', '90915507', '90752423', '90738421', '90725712', '90725083', '90722238', 33 | '90647220', '90604415', '90544478', '90379769', '90288341', '90183695', '90144066', 34 | '90108283', '90021771', '89914471', '89876284', '89852050', '89839033', '89812373', 35 | '89789699', '89786189', '89752620', '89636380', '89632889', '89525811', '89480625', 36 | '89464088', '89464025', '89463984', '89463925', '89445280', '89441793', '89430432', 37 | '89429877', '89416176', '89412750', '89409618', '89409485', '89409365', '89409292', 38 | '89409222', '89399738', '89399674', '89399526', '89355336', '89330241', '89308077', 39 | '89222240', '89140953', '89139942', '89134398', '89069355', '89049266', '89035735', 40 | '89004259', '88925790', '88925049', '88915838', '88912706', '88911548', '88899438', 41 | '88878890', '88837519', '88832555', '88824257', '88777952', '88752158', '88659061', 42 | '88615256', '88551434', '88375675', '88322134', '88322085', '88321996', '88321978', 43 | '88321950', '88321931', '88321919', '88321899', '88321830', '88321756', '88321710', 44 | '88321661', '88321632', '88321566', '88321550', '88321506', '88321475', '88321440', 45 | '88321409', '88321362', '88321321', '88321293', '88321226', '88232699', '88094874', 46 | '88090899', '88090784', '88089091', '88048808', '87938224', '87913318', '87905933', 47 | '87897358', '87856753', '87856461', '87827666', '87822008', '87821456', '87739137', 48 | '87734022', '87643633', '87624617', '87602909', '87548744', '87548689', '87548624', 49 | '87548550', '87548461', '87463201', '87385913', '87344048', '87078109', '87074784', 50 | '87004367', '86997632', '86997466', '86997303', '86997116', '86996474', '86995899', 51 | '86892769', '86892654', '86892569', '86892457', '86892347', '86892239', '86892124', 52 | '86798671', '86777307', '86762845', '86760008', '86759962', '86759944', '86759930', 53 | '86759922', '86759646', '86759638', '86759633', '86759622', '86759611', '86759602', 54 | '86759596', '86759591', '86759580', '86759572', '86759567', '86759558', '86759545', 55 | '86759534', '86749811', '86741502', '86741074', '86741059', '86741020', '86740897', 56 | '86694754', '86670104', '86651882', '86651875', '86651866', '86651828', '86651790', 57 | '86651767', '86651756', '86651735', '86651720', '86651708', '86618534', '86618526', 58 | '86594785', '86590937', '86550497', '86550481', '86550472', '86550453', '86550438', 59 | '86550429', '86550407', '86550381', '86550359', '86536071', '86536035', '86536014', 60 | '86535988', '86535963', '86535953', '86535932', '86535902', '86472491', '86472298', 61 | '86472236', '86472191', '86472108', '86471967', '86471899', '86471822', '86439022', 62 | '86438972', '86438902', '86438887', '86438867', '86438836', '86438818', '85850119', 63 | '85850075', '85850021', '85849945', '85849893', '85849837', '85849790', '85849740', 64 | '85849661', '85849620', '85849550', '85606096', '85564441', '85547709', '85471981', 65 | '85471317', '85471136', '85471073', '85470629', '85470456', '85470169', '85469996', 66 | '85469877', '85469775', '85469651', '85469331', '85469033', '85345768', '85345742', 67 | '85337900', '85337879', '85337860', '85337833', '85337797', '85322822', '85322810', 68 | '85322791', '85322745', '85317667', '85265742', '85265696', '85265618', '85265350', 69 | '85098457', '85057670', '85009890', '84755581', '84637437', '84637431', '84637393', 70 | '84637374', '84637355', '84637338', '84637321', '84637305', '84637283', '84637259', 71 | '84629399', '84629314', '84629233', '84629124', '84629065', '84628997', '84628933', 72 | '84628838', '84628777', '84628690', '84591581', '84591553', '84591511', '84591484', 73 | '84591468', '84591416', '84591386', '84591350', '84591308', '84572155', '84572107', 74 | '84503228', '84500221', '84403516', '84403496', '84403473', '84403442', '84075703', 75 | '84029659', '83933480', '83933459', '83933435', '83903298', '83903274', '83903258', 76 | '83752369', '83345186', '83116487', '83116446', '83116402', '83116334', '83116213', 77 | '82944248', '82941023', '82938777', '82936611', '82932735', '82918102', '82911085', 78 | '82888399', '82884263', '82883507', '82880996', '82875334', '82864060', '82831039', 79 | '82823385', '82795277', '82790832', '82775718', '82752022', '82730437', '82718126', 80 | '82661646', '82588279', '82588267', '82588261', '82588192', '82347066', '82056138', 81 | '81978722', '81211571', '81104145', '81069048', '81006768', '80788365', '80767582', 82 | '80759172', '80759144', '80759129', '80736927', '80661288', '80616304', '80602366', 83 | '80584625', '80561364', '80549878', '80549875', '80541470', '80539726', '80531328', 84 | '80513257', '80469816', '80406810', '80356781', '80334130', '80333252', '80332666', 85 | '80332389', '80311244', '80301070', '80295974', '80292252', '80286963', '80279504', 86 | '80278369', '80274371', '80249825', '80247284', '80223054', '80219559', '80209778', 87 | '80200279', '80164236', '80160900', '80153046', '80149560', '80144670', '80061205', 88 | '80046520', '80025644', '80014721', '80005213', '80004664', '80001653', '79990178', 89 | '79989283', '79947873', '79946002', '79941517', '79938786', '79932755', '79921178', 90 | '79911339', '79897603', '79883931', '79872574', '79846509', '79832150', '79828161', 91 | '79828156', '79828149', '79828146', '79828140', '79828139', '79828135', '79828123', 92 | '79820772', '79776809', '79776801', '79776788', '79776782', '79776772', '79776767', 93 | '79776760', '79776753', '79776736', '79776705', '79676183', '79676171', '79676166', 94 | '79676160', '79658242', '79658137', '79658130', '79658123', '79658119', '79658112', 95 | '79658100', '79658092', '79658089', '79658069', '79658054', '79633508', '79587857', 96 | '79587850', '79587842', '79587831', '79587825', '79587819', '79547908', '79477700', 97 | '79477692', '79440956', '79431176', '79428647', '79416896', '79406699', '79350633', 98 | '79350545', '79344765', '79339391', '79339383', '79339157', '79307345', '79293944', 99 | '79292623', '79274443', '79242798', '79184420', '79184386', '79184355', '79184269', 100 | '79183979', '79100314', '79100206', '79100064', '79090813', '79057834', '78967246', 101 | '78941571', '78927340', '78911467', '78909741', '78848006', '78628917', '78628908', 102 | '78628889', '78571306', '78571273', '78571253', '78508837', '78508791', '78448073', 103 | '78430940', '78408150', '78369548', '78323851', '78314301', '78307417', '78300457', 104 | '78287108', '78278945', '78259349', '78237192', '78231360', '78141031', '78100357', 105 | '78095793', '78084949', '78073873', '78073833', '78067868', '78067811', '78055014', 106 | '78041555', '78039240', '77948804', '77879624', '77837792', '77824937', '77816459', 107 | '77816208', '77801801', '77801767', '77776636', '77776610', '77505676', '77485156', 108 | '77478296', '77460928', '77327521', '77326428', '77278423', '77258908', '77252370', 109 | '77248841', '77239042', '77233843', '77230880', '77200256', '77198140', '77196405', 110 | '77193456', '77186557', '77185568', '77181823', '77170422', '77164604', '77163389', 111 | '77160103', '77159392', '77150721', '77146204', '77141824', '77129604', '77123259', 112 | '77113014', '77103247', '77101924', '77100165', '77098190', '77094986', '77088637', 113 | '77073399', '77062405', '77044198', '77036923', '77017092', '77007016', '76999924', 114 | '76977678', '76944015', '76923087', '76912696', '76890184', '76862282', '76852434', 115 | '76829683', '76794256', '76780755', '76762181', '76732277', '76718569', '76696048', 116 | '76691568', '76689003', '76674746', '76651230', '76640301', '76615315', '76598528', 117 | '76571947', '76551820', '74178127', '74157245', '74090991', '74012309', '74001789', 118 | '73910511', '73613471', '73605647', '73605082', '73503704', '73380636', '73277303', 119 | '73274683', '73252108', '73252085', '73252070', '73252039', '73252025', '73251974', 120 | '73135779', '73087531', '73044025', '73008658', '72998118', '72997953', '72847091', 121 | '72833384', '72830909', '72828999', '72823633', '72793092', '72757626', '71157154', 122 | '71131579', '71128551', '71122253', '71082760', '71078326', '71075369', '71057216', 123 | '70812997', '70384625', '70347260', '70328937', '70313267', '70312950', '70255825', 124 | '70238893', '70237566', '70237072', '70230665', '70228737', '70228729', '70175557', 125 | '70175401', '70173259', '70172591', '70170835', '70140724', '70139606', '70053923', 126 | '69067886', '69063732', '69055974', '69055708', '69031254', '68960022', '68957926', 127 | '68957556', '68953383', '68952755', '68946828', '68483371', '68120861', '68065606', 128 | '68064545', '68064493', '67646436', '67637525', '67632961', '66984317', '66968934', 129 | '66968328', '66491589', '66475786', '66473308', '65946462', '65635220', '65632553', 130 | '65443309', '65437683', '63260222', '63253665', '63253636', '63253628', '63253610', 131 | '63253572', '63252767', '63252672', '63252636', '63252537', '63252440', '63252329', 132 | '63252155', '62888876', '62238064', '62039365', '62038016', '61925813', '60957024', 133 | '60146286', '59523598', '59489460', '59480461', '59160354', '59109234', '59089006', 134 | '58595549', '57406062', '56678797', '55001342', '55001340', '55001336', '55001330', 135 | '55001328', '55001325', '55001311', '55001305', '55001298', '55001290', '55001283', 136 | '55001278', '55001272', '55001265', '55001262', '55001253', '55001246', '55001242', 137 | '55001236', '54907997', '54798827', '54782693', '54782689', '54782688', '54782676', 138 | '54782673', '54782671', '54782662', '54782649', '54782636', '54782630', '54782628', 139 | '54782627', '54782624', '54782621', '54782620', '54782615', '54782613', '54782608', 140 | '54782604', '54782600', '54767237', '54766779', '54755814', '54755674', '54730253', 141 | '54709338', '54667667', '54667657', '54667639', '54646201', '54407212', '54236114', 142 | '54234220', '54233181', '54232788', '54232407', '54177960', '53991319', '53932970', 143 | '53888106', '53887128', '53885944', '53885094', '53884497', '53819985', '53812640', 144 | '53811866', '53790628', '53785053', '53782838', '53768406', '53763191', '53763163', 145 | '53763148', '53763104', '53763092', '53576302', '53576157', '53573472', '53560183', 146 | '53523648', '53516634', '53514474', '53510917', '53502297', '53492224', '53467240', 147 | '53467122', '53437115', '53436579', '53435710', '53415115', '53377875', '53365337', 148 | '53350165', '53337979', '53332925', '53321283', '53318758', '53307049', '53301773', 149 | '53289364', '53286367', '53259948', '53242892', '53239518', '53230890', '53218625', 150 | '53184121', '53148662', '53129280', '53116507', '53116486', '52980893', '52980652', 151 | '52971002', '52950276', '52950259', '52944714', '52934397', '52932994', '52924939', 152 | '52887083', '52877145', '52858258', '52858046', '52840214', '52829673', '52818774', 153 | '52814054', '52805448', '52798019', '52794801', '52786111', '52774750', '52748816', 154 | '52745187', '52739313', '52738109', '52734410', '52734406', '52734401', '52515005', 155 | '52056818', '52039757', '52034057', '50899381', '50738883', '50726018', '50695984', 156 | '50695978', '50695961', '50695931', '50695913', '50695902', '50695898', '50695896', 157 | '50695885', '50695852', '50695843', '50695829', '50643222', '50591997', '50561827', 158 | '50550829', '50541472', '50527581', '50527317', '50527206', '50527094', '50526976', 159 | '50525931', '50525764', '50518363', '50498312', '50493019', '50492927', '50492881', 160 | '50492863', '50492772', '50492741', '50492688', '50492454', '50491686', '50491675', 161 | '50491602', '50491550', '50491467', '50488409', '50485177', '48683433', '48679853', 162 | '48678381', '48626023', '48623059', '48603183', '48599041', '48595555', '48576507', 163 | '48574581', '48574425', '48547849', '48542371', '48518705', '48494395', '48493321', 164 | '48491545', '48471207', '48471161', '48471085', '48468239', '48416035', '48415577', 165 | '48415515', '48297597', '48225865', '48224037', '48223553', '48213383', '48211439', 166 | '48206757', '48195685', '48193981', '48154955', '48128811', '48105995', '48105727', 167 | '48105441', '48105085', '48101717', '48101691', '48101637', '48101569', '48101543', 168 | '48085839', '48085821', '48085797', '48085785', '48085775', '48085765', '48085749', 169 | '48085717', '48085687', '48085377', '48085189', '48085119', '48085043', '48084991', 170 | '48084747', '48084139', '48084075', '48055511', '48055403', '48054259', '48053917', 171 | '47378253', '47359989', '47344793', '47344083', '47336927', '47335827', '47316383', 172 | '47315813', '47312213', '47295745', '47294471', '47259467', '47256015', '47255529', 173 | '47253649', '47207791', '47206309', '47189383', '47172333', '47170495', '47166223', '47149681', '47146967', '47126915', '47126883', '47108297', '47091823', '47084039', 174 | '47080883', '47058549', '47056435', '47054703', '47041395', '47035325', '47035143', 175 | '47027547', '47016851', '47006665', '46854213', '46128743', '45035163', '43053503', 176 | '41968283', '41958265', '40707993', '40706971', '40685165', '40684953', '40684575', 177 | '40683867', '40683021', '39853417', '39806033', '39757139', '38391523', '37595169', 178 | '37584503', '35696501', '29593529', '28100441', '27330071', '26950993', '26011757', 179 | '26010983', '26010603', '26004793', '26003621', '26003575', '26003405', '26003373', 180 | '26003307', '26003225', '26003189', '26002929', '26002863', '26002749', '26001477', 181 | '25641541', '25414671', '25410705', '24973063', '20648491', '20621099', '17802317', 182 | '17171597', '17141619', '17141381', '17139321', '17121903', '16898605', '16886449', 183 | '14523439', '14104635', '14054225', '9317965' 184 | ] 185 | var urlb64 = 'aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dpemFyZGZvcmNlbC9hcnRpY2xlL2RldGFpbHMv' 186 | var plugin = function(hook) { 187 | hook.doneEach(function() { 188 | for (var i = 0; i < 5; i++) { 189 | var idx = Math.trunc(Math.random() * ids.length) 190 | new Image().src = atob(urlb64) + ids[idx] 191 | } 192 | }) 193 | } 194 | var plugins = window.$docsify.plugins || [] 195 | plugins.push(plugin) 196 | window.$docsify.plugins = plugins 197 | })() -------------------------------------------------------------------------------- /asset/docsify-cnzz.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var plugin = function(hook) { 3 | hook.doneEach(function() { 4 | var sc = document.createElement('script') 5 | sc.src = 'https://s5.cnzz.com/z_stat.php?id=' + 6 | window.$docsify.cnzzId + '&online=1&show=line' 7 | document.querySelector('article').appendChild(sc) 8 | }) 9 | } 10 | var plugins = window.$docsify.plugins || [] 11 | plugins.push(plugin) 12 | window.$docsify.plugins = plugins 13 | })() -------------------------------------------------------------------------------- /asset/docsify-copy-code.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * docsify-copy-code 3 | * v2.1.0 4 | * https://github.com/jperasmus/docsify-copy-code 5 | * (c) 2017-2019 JP Erasmus 6 | * MIT license 7 | */ 8 | !function(){"use strict";function r(o){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o})(o)}!function(o,e){void 0===e&&(e={});var t=e.insertAt;if(o&&"undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],c=document.createElement("style");c.type="text/css","top"===t&&n.firstChild?n.insertBefore(c,n.firstChild):n.appendChild(c),c.styleSheet?c.styleSheet.cssText=o:c.appendChild(document.createTextNode(o))}}(".docsify-copy-code-button,.docsify-copy-code-button span{cursor:pointer;transition:all .25s ease}.docsify-copy-code-button{position:absolute;z-index:1;top:0;right:0;overflow:visible;padding:.65em .8em;border:0;border-radius:0;outline:0;font-size:1em;background:grey;background:var(--theme-color,grey);color:#fff;opacity:0}.docsify-copy-code-button span{border-radius:3px;background:inherit;pointer-events:none}.docsify-copy-code-button .error,.docsify-copy-code-button .success{position:absolute;z-index:-100;top:50%;left:0;padding:.5em .65em;font-size:.825em;opacity:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.docsify-copy-code-button.error .error,.docsify-copy-code-button.success .success{opacity:1;-webkit-transform:translate(-115%,-50%);transform:translate(-115%,-50%)}.docsify-copy-code-button:focus,pre:hover .docsify-copy-code-button{opacity:1}"),document.querySelector('link[href*="docsify-copy-code"]')&&console.warn("[Deprecation] Link to external docsify-copy-code stylesheet is no longer necessary."),window.DocsifyCopyCodePlugin={init:function(){return function(o,e){o.ready(function(){console.warn("[Deprecation] Manually initializing docsify-copy-code using window.DocsifyCopyCodePlugin.init() is no longer necessary.")})}}},window.$docsify=window.$docsify||{},window.$docsify.plugins=[function(o,s){o.doneEach(function(){var o=Array.apply(null,document.querySelectorAll("pre[data-lang]")),c={buttonText:"Copy to clipboard",errorText:"Error",successText:"Copied"};s.config.copyCode&&Object.keys(c).forEach(function(t){var n=s.config.copyCode[t];"string"==typeof n?c[t]=n:"object"===r(n)&&Object.keys(n).some(function(o){var e=-1',''.concat(c.buttonText,""),''.concat(c.errorText,""),''.concat(c.successText,""),""].join("");o.forEach(function(o){o.insertAdjacentHTML("beforeend",e)})}),o.mounted(function(){document.querySelector(".content").addEventListener("click",function(o){if(o.target.classList.contains("docsify-copy-code-button")){var e="BUTTON"===o.target.tagName?o.target:o.target.parentNode,t=document.createRange(),n=e.parentNode.querySelector("code"),c=window.getSelection();t.selectNode(n),c.removeAllRanges(),c.addRange(t);try{document.execCommand("copy")&&(e.classList.add("success"),setTimeout(function(){e.classList.remove("success")},1e3))}catch(o){console.error("docsify-copy-code: ".concat(o)),e.classList.add("error"),setTimeout(function(){e.classList.remove("error")},1e3)}"function"==typeof(c=window.getSelection()).removeRange?c.removeRange(t):"function"==typeof c.removeAllRanges&&c.removeAllRanges()}})})}].concat(window.$docsify.plugins||[])}(); 9 | //# sourceMappingURL=docsify-copy-code.min.js.map 10 | -------------------------------------------------------------------------------- /asset/prism-darcula.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Darcula theme 3 | * 4 | * Adapted from a theme based on: 5 | * IntelliJ Darcula Theme (https://github.com/bulenkov/Darcula) 6 | * 7 | * @author Alexandre Paradis 8 | * @version 1.0 9 | */ 10 | 11 | code[class*="lang-"], 12 | pre[data-lang] { 13 | color: #a9b7c6 !important; 14 | background-color: #2b2b2b !important; 15 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 16 | direction: ltr; 17 | text-align: left; 18 | white-space: pre; 19 | word-spacing: normal; 20 | word-break: normal; 21 | line-height: 1.5; 22 | 23 | -moz-tab-size: 4; 24 | -o-tab-size: 4; 25 | tab-size: 4; 26 | 27 | -webkit-hyphens: none; 28 | -moz-hyphens: none; 29 | -ms-hyphens: none; 30 | hyphens: none; 31 | } 32 | 33 | pre[data-lang]::-moz-selection, pre[data-lang] ::-moz-selection, 34 | code[class*="lang-"]::-moz-selection, code[class*="lang-"] ::-moz-selection { 35 | color: inherit; 36 | background: rgba(33, 66, 131, .85); 37 | } 38 | 39 | pre[data-lang]::selection, pre[data-lang] ::selection, 40 | code[class*="lang-"]::selection, code[class*="lang-"] ::selection { 41 | color: inherit; 42 | background: rgba(33, 66, 131, .85); 43 | } 44 | 45 | /* Code blocks */ 46 | pre[data-lang] { 47 | padding: 1em; 48 | margin: .5em 0; 49 | overflow: auto; 50 | } 51 | 52 | :not(pre) > code[class*="lang-"], 53 | pre[data-lang] { 54 | background: #2b2b2b; 55 | } 56 | 57 | /* Inline code */ 58 | :not(pre) > code[class*="lang-"] { 59 | padding: .1em; 60 | border-radius: .3em; 61 | } 62 | 63 | .token.comment, 64 | .token.prolog, 65 | .token.cdata { 66 | color: #808080; 67 | } 68 | 69 | .token.delimiter, 70 | .token.boolean, 71 | .token.keyword, 72 | .token.selector, 73 | .token.important, 74 | .token.atrule { 75 | color: #cc7832; 76 | } 77 | 78 | .token.operator, 79 | .token.punctuation, 80 | .token.attr-name { 81 | color: #a9b7c6; 82 | } 83 | 84 | .token.tag, 85 | .token.tag .punctuation, 86 | .token.doctype, 87 | .token.builtin { 88 | color: #e8bf6a; 89 | } 90 | 91 | .token.entity, 92 | .token.number, 93 | .token.symbol { 94 | color: #6897bb; 95 | } 96 | 97 | .token.property, 98 | .token.constant, 99 | .token.variable { 100 | color: #9876aa; 101 | } 102 | 103 | .token.string, 104 | .token.char { 105 | color: #6a8759; 106 | } 107 | 108 | .token.attr-value, 109 | .token.attr-value .punctuation { 110 | color: #a5c261; 111 | } 112 | 113 | .token.attr-value .punctuation:first-child { 114 | color: #a9b7c6; 115 | } 116 | 117 | .token.url { 118 | color: #287bde; 119 | text-decoration: underline; 120 | } 121 | 122 | .token.function { 123 | color: #ffc66d; 124 | } 125 | 126 | .token.regex { 127 | background: #364135; 128 | } 129 | 130 | .token.bold { 131 | font-weight: bold; 132 | } 133 | 134 | .token.italic { 135 | font-style: italic; 136 | } 137 | 138 | .token.inserted { 139 | background: #294436; 140 | } 141 | 142 | .token.deleted { 143 | background: #484a4a; 144 | } 145 | 146 | code.lang-css .token.property, 147 | code.lang-css .token.property + .token.punctuation { 148 | color: #a9b7c6; 149 | } 150 | 151 | code.lang-css .token.id { 152 | color: #ffc66d; 153 | } 154 | 155 | code.lang-css .token.selector > .token.class, 156 | code.lang-css .token.selector > .token.attribute, 157 | code.lang-css .token.selector > .token.pseudo-class, 158 | code.lang-css .token.selector > .token.pseudo-element { 159 | color: #ffc66d; 160 | } -------------------------------------------------------------------------------- /asset/prism-python.min.js: -------------------------------------------------------------------------------- 1 | Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"string-interpolation":{pattern:/(?:f|rf|fr)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|rb|br)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/im,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python; -------------------------------------------------------------------------------- /asset/search.min.js: -------------------------------------------------------------------------------- 1 | !function(){var h={},f={EXPIRE_KEY:"docsify.search.expires",INDEX_KEY:"docsify.search.index"};function l(e){var n={"&":"&","<":"<",">":">",'"':""","'":"'"};return String(e).replace(/[&<>"']/g,function(e){return n[e]})}function p(e){return e.text||"table"!==e.type||(e.cells.unshift(e.header),e.text=e.cells.map(function(e){return e.join(" | ")}).join(" |\n ")),e.text}function u(r,e,i,o){void 0===e&&(e="");var s,n=window.marked.lexer(e),c=window.Docsify.slugify,d={};return n.forEach(function(e){if("heading"===e.type&&e.depth<=o){var n=function(e){void 0===e&&(e="");var a={};return{str:e=e&&e.replace(/^'/,"").replace(/'$/,"").replace(/(?:^|\s):([\w-]+:?)=?([\w-%]+)?/g,function(e,n,t){return-1===n.indexOf(":")?(a[n]=t&&t.replace(/"/g,"")||!0,""):e}).trim(),config:a}}(e.text),t=n.str,a=n.config;s=a.id?i.toURL(r,{id:c(a.id)}):i.toURL(r,{id:c(l(e.text))}),d[s]={slug:s,title:t,body:""}}else{if(!s)return;d[s]?d[s].body?(e.text=p(e),d[s].body+="\n"+(e.text||"")):(e.text=p(e),d[s].body=d[s].body?d[s].body+e.text:e.text):d[s]={slug:s,title:"",body:""}}}),c.clear(),d}function c(e){var r=[],i=[];Object.keys(h).forEach(function(n){i=i.concat(Object.keys(h[n]).map(function(e){return h[n][e]}))});var o=(e=e.trim()).split(/[\s\-,\\/]+/);1!==o.length&&(o=[].concat(e,o));function n(e){var n=i[e],s=0,c="",d=n.title&&n.title.trim(),p=n.body&&n.body.trim(),t=n.slug||"";if(d&&(o.forEach(function(e){var n,t=new RegExp(e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&"),"gi"),a=-1;if(n=d?d.search(t):-1,a=p?p.search(t):-1,0<=n||0<=a){s+=0<=n?3:0<=a?2:0,a<0&&(a=0);var r,i=0;i=0==(r=a<11?0:a-10)?70:a+e.length+60,p&&i>p.length&&(i=p.length);var o="..."+l(p).substring(r,i).replace(t,function(e){return''+e+""})+"...";c+=o}}),0\n\n

'+e.title+"

\n

"+e.content+"

\n
\n"}),t.classList.add("show"),a.classList.add("show"),t.innerHTML=s||'

'+m+"

",d.hideOtherSidebarContent&&(r.classList.add("hide"),i.classList.add("hide"))}function a(e){d=e}function o(e,n){var t=n.router.parse().query.s;a(e),Docsify.dom.style("\n.sidebar {\n padding-top: 0;\n}\n\n.search {\n margin-bottom: 20px;\n padding: 6px;\n border-bottom: 1px solid #eee;\n}\n\n.search .input-wrap {\n display: flex;\n align-items: center;\n}\n\n.search .results-panel {\n display: none;\n}\n\n.search .results-panel.show {\n display: block;\n}\n\n.search input {\n outline: none;\n border: none;\n width: 100%;\n padding: 0 7px;\n line-height: 36px;\n font-size: 14px;\n border: 1px solid transparent;\n}\n\n.search input:focus {\n box-shadow: 0 0 5px var(--theme-color, #42b983);\n border: 1px solid var(--theme-color, #42b983);\n}\n\n.search input::-webkit-search-decoration,\n.search input::-webkit-search-cancel-button,\n.search input {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n.search .clear-button {\n cursor: pointer;\n width: 36px;\n text-align: right;\n display: none;\n}\n\n.search .clear-button.show {\n display: block;\n}\n\n.search .clear-button svg {\n transform: scale(.5);\n}\n\n.search h2 {\n font-size: 17px;\n margin: 10px 0;\n}\n\n.search a {\n text-decoration: none;\n color: inherit;\n}\n\n.search .matching-post {\n border-bottom: 1px solid #eee;\n}\n\n.search .matching-post:last-child {\n border-bottom: 0;\n}\n\n.search p {\n font-size: 14px;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.search p.empty {\n text-align: center;\n}\n\n.app-name.hide, .sidebar-nav.hide {\n display: none;\n}"),function(e){void 0===e&&(e="");var n='
\n \n
\n \n \n \n \n \n
\n
\n
\n ',t=Docsify.dom.create("div",n),a=Docsify.dom.find("aside");Docsify.dom.toggleClass(t,"search"),Docsify.dom.before(a,t)}(t),function(){var e,n=Docsify.dom.find("div.search"),t=Docsify.dom.find(n,"input"),a=Docsify.dom.find(n,".input-wrap");Docsify.dom.on(n,"click",function(e){return-1===["A","H2","P","EM"].indexOf(e.target.tagName)&&e.stopPropagation()}),Docsify.dom.on(t,"input",function(n){clearTimeout(e),e=setTimeout(function(e){return r(n.target.value.trim())},100)}),Docsify.dom.on(a,"click",function(e){"INPUT"!==e.target.tagName&&(t.value="",r())})}(),t&&setTimeout(function(e){return r(t)},500)}function s(e,n){a(e),function(e,n){var t=Docsify.dom.getNode('.search input[type="search"]');if(t)if("string"==typeof e)t.placeholder=e;else{var a=Object.keys(e).filter(function(e){return-1ul:nth-child(1) { 3 | display: none; 4 | } 5 | 6 | #main>ul:nth-child(2) { 7 | display: none; 8 | } 9 | 10 | .markdown-section h1 { 11 | margin: 3rem 0 2rem 0; 12 | } 13 | 14 | .markdown-section h2 { 15 | margin: 2rem 0 1rem; 16 | } 17 | 18 | img, 19 | pre { 20 | border-radius: 8px; 21 | } 22 | 23 | .content, 24 | .sidebar, 25 | .markdown-section, 26 | body, 27 | .search input { 28 | background-color: rgba(243, 242, 238, 1) !important; 29 | } 30 | 31 | @media (min-width:600px) { 32 | .sidebar-toggle { 33 | background-color: #f3f2ee; 34 | } 35 | } 36 | 37 | .docsify-copy-code-button { 38 | background: #f8f8f8 !important; 39 | color: #7a7a7a !important; 40 | } 41 | 42 | body { 43 | /*font-family: Microsoft YaHei, Source Sans Pro, Helvetica Neue, Arial, sans-serif !important;*/ 44 | } 45 | 46 | .markdown-section>p { 47 | font-size: 16px !important; 48 | } 49 | 50 | .markdown-section pre>code { 51 | font-family: Consolas, Roboto Mono, Monaco, courier, monospace !important; 52 | font-size: .9rem !important; 53 | 54 | } 55 | 56 | /*.anchor span { 57 | color: rgb(66, 185, 131); 58 | }*/ 59 | 60 | section.cover h1 { 61 | margin: 0; 62 | } 63 | 64 | body>section>div.cover-main>ul>li>a { 65 | color: #42b983; 66 | } 67 | 68 | .markdown-section img { 69 | box-shadow: 7px 9px 10px #aaa !important; 70 | } 71 | 72 | 73 | pre { 74 | background-color: #f3f2ee !important; 75 | } 76 | 77 | @media (min-width:600px) { 78 | pre code { 79 | /*box-shadow: 2px 1px 20px 2px #aaa;*/ 80 | /*border-radius: 10px !important;*/ 81 | padding-left: 20px !important; 82 | } 83 | } 84 | 85 | @media (max-width:600px) { 86 | pre { 87 | padding-left: 0px !important; 88 | padding-right: 0px !important; 89 | } 90 | } 91 | 92 | .markdown-section pre { 93 | padding-left: 0 !important; 94 | padding-right: 0px !important; 95 | box-shadow: 2px 1px 20px 2px #aaa; 96 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
now loading...
21 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /update.sh: -------------------------------------------------------------------------------- 1 | git add -A 2 | git commit -am "$(date "+%Y-%m-%d %H:%M:%S")" 3 | git push --------------------------------------------------------------------------------