pcolormesh 网格和阴影#

axes.Axes.pcolormeshpcolor 有一些选项用于网格的布局以及网格点之间的阴影处理。

通常,如果 Z 的形状为 (M, N),那么网格 XY 可以根据 shading 关键字参数的值,指定为形状 (M+1, N+1)(M, N)。注意,下面我们将向量 x 指定为长度 N 或 N+1,将 y 指定为长度 M 或 M+1,而 pcolormesh 内部会根据输入向量生成网格矩阵 XY

import matplotlib.pyplot as plt
import numpy as np

平面着色#

假设最少的网格规范是 shading='flat' ,如果网格在每个维度上比数据大一,即形状为 (M+1, N+1) 。在这种情况下,XY 指定了用 Z 中的值着色的四边形的角。这里我们用 XY 指定了 (3, 5) 四边形的边,它们是 (4, 6)

nrows = 3
ncols = 5
Z = np.arange(nrows * ncols).reshape(nrows, ncols)
x = np.arange(ncols + 1)
y = np.arange(nrows + 1)

fig, ax = plt.subplots()
ax.pcolormesh(x, y, Z, shading='flat', vmin=Z.min(), vmax=Z.max())


def _annotate(ax, x, y, title):
    # this all gets repeated below:
    X, Y = np.meshgrid(x, y)
    ax.plot(X.flat, Y.flat, 'o', color='m')
    ax.set_xlim(-0.7, 5.2)
    ax.set_ylim(-0.7, 3.2)
    ax.set_title(title)

_annotate(ax, x, y, "shading='flat'")
shading='flat'

平面着色,相同形状的网格#

然而,通常情况下,提供的数据中 XYZ 的形状匹配。虽然这对其他 shading 类型有意义,但在 shading='flat' 时是不允许的。历史上,Matplotlib 在这种情况下会默默地丢弃 Z 的最后一行和最后一列,以匹配 Matlab 的行为。如果仍然希望这种行为,只需手动丢弃最后一行和最后一列:

x = np.arange(ncols)  # note *not* ncols + 1 as before
y = np.arange(nrows)
fig, ax = plt.subplots()
ax.pcolormesh(x, y, Z[:-1, :-1], shading='flat', vmin=Z.min(), vmax=Z.max())
_annotate(ax, x, y, "shading='flat': X, Y, C same shape")
shading='flat': X, Y, C same shape

最近邻着色,相同形状的网格#

通常,当用户使 XYZ 具有相同形状时,他们并不意味着要删除数据的一行和一列。对于这种情况,Matplotlib 允许 shading='nearest' 并将彩色四边形中心置于网格点上。

如果传递的网格形状不正确,并且使用了 shading='nearest',则会引发错误。

fig, ax = plt.subplots()
ax.pcolormesh(x, y, Z, shading='nearest', vmin=Z.min(), vmax=Z.max())
_annotate(ax, x, y, "shading='nearest'")
shading='nearest'

自动阴影#

用户可能希望代码自动选择使用哪种方式,在这种情况下,shading='auto' 将根据 XYZ 的形状决定使用 'flat' 还是 'nearest' 着色。

fig, axs = plt.subplots(2, 1, layout='constrained')
ax = axs[0]
x = np.arange(ncols)
y = np.arange(nrows)
ax.pcolormesh(x, y, Z, shading='auto', vmin=Z.min(), vmax=Z.max())
_annotate(ax, x, y, "shading='auto'; X, Y, Z: same shape (nearest)")

ax = axs[1]
x = np.arange(ncols + 1)
y = np.arange(nrows + 1)
ax.pcolormesh(x, y, Z, shading='auto', vmin=Z.min(), vmax=Z.max())
_annotate(ax, x, y, "shading='auto'; X, Y one larger than Z (flat)")
shading='auto'; X, Y, Z: same shape (nearest), shading='auto'; X, Y one larger than Z (flat)

Gouraud 着色#

Gouraud 着色 也可以指定,其中四边形中的颜色在线性插值网格点之间。XYZ 的形状必须相同。

fig, ax = plt.subplots(layout='constrained')
x = np.arange(ncols)
y = np.arange(nrows)
ax.pcolormesh(x, y, Z, shading='gouraud', vmin=Z.min(), vmax=Z.max())
_annotate(ax, x, y, "shading='gouraud'; X, Y same shape as Z")

plt.show()
shading='gouraud'; X, Y same shape as Z

参考文献

以下函数、方法、类和模块的使用在本示例中展示:

由 Sphinx-Gallery 生成的图库