matplotlib 的基础结构

2022/3/13 matplotlib

用了很久的 matplotlib 用来绘制图片,但是对于库本身,涉猎过少,都是草草搜索接口,于是准备整理一下,以后看文档更加得心应手。

首先看看 Matplotlib 图的组成部分。

# Figure

首先注意位于左下角的 Figure,这一整张图形,就是一个 FigureFigure 包含了全部绘图区域(Axes,titles, figure legends, colorbars, 等等)。

import matplotlib.pyplot as plt
fig = plt.figure()
1
2

# Axes

Axes 可以理解为“绘图区域”。 是包含绘制数据的区域的 Figure 里的 Artist,通常包括两个(或在 3D 的情况下为三个)Axis 对象(注意 AxesAxis 之间的区别),后者提供刻度和刻度标签为轴中的数据提供比例。 每个轴也有一个标题(通过 set_title() 设置)、一个 x 标签(通过 set_xlabel() 设置)和一个通过 set_ylabel() 设置的 y 标签。

Axes 类及其成员函数是使用 OOP 接口的主要入口点,并且在其上定义了大多数绘图方法,OOP yyds。

::: tips 关于 Axes 如何理解 “This is what you think of as 'a plot’, it is the region of the image with the data space. ”(Ver. 3.1.1 Page13) 旧的官方文档是如此解释的,于是便理解成了绘图区域。 :::

# Axis

Axis 对象设置比例和范围并生成刻度(轴上的标记)和刻度标签(标记刻度的字符串)。 刻度的位置由 Locator 对象确定,刻度标签字符串由 Formatter 格式化。 正确的定位和格式化的组合可以很好地控制刻度位置和标签。

# Artist

基本上,在 Figure 上可见的所有东西都是 Artist(甚至是 Figure、 Axes 和 Axis 对象)。 这包括 Text 对象、 Line2D 对象、 集合对象、 Patch 对象等。 当 Figure 被渲染时,所有的 Artist 都被绘制到画布上。 大多数 Artist 都被绘制在 Axes 上; 这样的 Artist 不能被多个 Axes 共享,也不能从一个 Axes 移动到另一个 Axes。

# 其他事项

# 输入数据类型

numpy.arraynumpy.ma.masked_array

# Latex 支持

ax.set_title(r'$\sigma_i=15$')
1

# 注解

通过 ax.annotate() 可添加注解,详见 Basic annotation (opens new window)Advanced Annotations (opens new window)

# 图例

Matplotlib 中的图例在布局、放置以及它们可以代表的艺术家方面非常灵活。 详见 Legend guide (opens new window)

# 坐标轴的缩放的刻度

除了线性刻度,Matplotlib 还提供非线性刻度,例如对数刻度。 由于对数尺度的使用如此之多,因此也有直接的方法,如 loglog、 semilogx 和 semilogy。 有关其他示例,参见 https://matplotlib.org/stable/gallery/scales/scales.html

# 定位和格式化

最简单的方式是使用 set_x/yticks,也可以使用其他的定位 (opens new window)格式化 (opens new window)程序。

# 多坐标轴

简单的添加一个额外的坐标轴可以用 twinxtwiny。 更多可以参见 https://matplotlib.org/stable/gallery/subplots_axes_and_figures/secondary_axis.html

# Colormaps

都是派生自 ScalarMappable 对象的 Artists。 都可以将 vmin 和 vmax 之间的线性映射设置为 cmap 指定的颜色映射。 Matplotlib 自带了许多颜色图 (opens new window)

# 规范化

有时我们希望数据到颜色图的非线性映射。 我们通过为 ScalarMappable 提供 norm 参数而不是 vmin 和 vmax 来做到这一点。 更多规范化显示在 Colormap Normalization (opens new window)

# Colorbars

添加 Colorbars 提供了将颜色与基础数据相关联的信息。 颜色条是图形级别的 Artists,并附加到 ScalarMappable(在其中获取有关规范和颜色图的信息),并且通常从父 Axes 中获取空间。 Colorbars 的放置可能很复杂:有关详细信息,请参阅放置 Colorbars (opens new window)。 还可以使用 extend 关键字更改 Colorbars 的外观以在末端添加箭头,并通过缩小和纵横比来控制大小。 最后,Colorbars 将具有适合规范的默认定位器和格式化程序。 这些可以像其他 Axis 对象一样更改。

# 复杂的 Axes 排列

使用 subplot_mosaic 可以实现更复杂的布局,其中 Axes 对象跨越列或行。 Matplotlib 具有用于排列 Axes 的非常复杂的工具:参见 https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html 和 https://matplotlib.org/stable/tutorials/provisional/mosaic.html

# 图形类型

参见 https://matplotlib.org/stable/plot_types/index.html

Last Updated: 2023-10-29T08:26:04.000Z