pcolormesh 網格和陰影#

axes.Axes.pcolormeshpcolor 有一些選項可用於如何配置網格以及網格點之間的陰影。

一般而言,如果 *Z* 的形狀為 *(M,N)*,則可以使用形狀為 *(M+1,N+1)* 或 *(M,N)* 指定網格 *X* 和 *Y*,具體取決於 shading 關鍵字引數。請注意,以下我們將向量 *x* 指定為長度 N 或 N+1,將 *y* 指定為長度 M 或 M+1,並且 pcolormesh 在內部從輸入向量建立網格矩陣 *X* 和 *Y*。

import matplotlib.pyplot as plt
import numpy as np

平面陰影#

假設最少的網格規格是 shading='flat',如果網格在每個維度中都比資料大一,即形狀為 *(M+1,N+1)*。在這種情況下,*X* 和 *Y* 指定用 *Z* 中的值著色的四邊形的角。在此,我們使用 *(4, 6)* 的 *X* 和 *Y* 來指定 *(3, 5)* 四邊形的邊。

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'

平面陰影,相同形狀網格#

但是,通常會提供 *X* 和 *Y* 與 *Z* 的形狀相符的資料。雖然這對於其他 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

最接近的陰影,相同形狀網格#

通常,使用者在使 *X*、*Y* 和 *Z* 的形狀都相同時,並非是指捨棄資料的列和欄。對於這種情況,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' 會根據 *X*、*Y* 和 *Z* 的形狀決定是否使用「平面」或「最接近」陰影。

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)

高洛德陰影#

也可以指定 高洛德陰影,其中四邊形中的顏色在網格點之間進行線性內插。*X*、*Y*、*Z* 的形狀必須相同。

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

參考資料

此範例中顯示了以下函式、方法、類別和模組的使用

指令碼的總執行時間: (0 分鐘 4.959 秒)

此圖庫由 Sphinx-Gallery 生成