在 Python Matplotlib 中生成反向色彩圖

  1. 在 Python Matplotlib 中的色彩圖(Colormaps)
  2. 在 Matplotlib Python 中使用 _r 進行反向顏色對映
  3. 在 Matplotlib Python 中使用 matplotlib. colors.Colormap.reversed() 反轉 Colormap
在 Python Matplotlib 中生成反向色彩圖

色彩圖 Colormap 是一種將資料值對映到顏色的簡單方法。反轉顏色圖意味著反轉每個值的色彩圖。假設我們有一個色彩圖,其中較低的值被對映到黃色,較高的值被對映到紅色。通過反轉 colormap,較低的值現在被對映到紅色,較高的值被對映到黃色。本教程解釋了在 Python Matplotlib 中反轉色彩圖的各種方法。

在 Python Matplotlib 中的色彩圖(Colormaps)

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(9)
y = [9, 2, 8, 4, 5, 7, 6, 8, 7]

plt.scatter(x, y, c=y, cmap="viridis")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Virdis colormap")
plt.colorbar()
plt.show()

輸出:

Matplotlib Python 中的 Colormaps

它建立了一個散點圖,其 y 值被對映到 viridis colormap。這意味著 y 值較低的點將呈現深藍色,y 值較高的點將呈現黃色,而中間的點將呈現藍色和綠色。

我們還可以在圖的右側看到一個顏色條,它顯示了 y 不同值的顏色對映。

在 Matplotlib Python 中使用 _r 進行反向顏色對映

在 Matplotlib 中,我們可以通過在 colormap 名稱的末尾新增 _r 來反轉 colormap,例如 cmap='viridis_r'將簡單地反轉 viridis colormap。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(9)
y = [9, 2, 8, 4, 5, 7, 6, 8, 7]

plt.scatter(x, y, c=y, cmap="viridis_r")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Inverse Virdis colormap")
plt.colorbar()
plt.show()

輸出:

在 Matplotlib Python 中通過在結尾新增_r 來反轉 Colormaps

它建立了一個散點圖,其 y 值被對映到反轉的 viridis colormap 上。因此,圖中數值較高的點得到深藍色,數值較低的點得到黃色。

我們還可以看到,在這個例子中,右邊的顏色條已經反轉了顏色。

在 Matplotlib Python 中使用 matplotlib. colors.Colormap.reversed() 反轉 Colormap

另一種在 Python 中反轉 Colormap 的方法是使用 matplotlib.color.Colormap.reversed() 方法來建立反轉的 Colormap。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

x = np.arange(9)
y = [9, 2, 8, 4, 5, 7, 6, 8, 7]

initial_cmap = cm.get_cmap("viridis")
reversed_cmap = initial_cmap.reversed()

plt.scatter(x, y, c=y, cmap=reversed_cmap)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Inverse Virdis colormap")
plt.colorbar()
plt.show()

輸出:

在 Matplotlib Python 中使用逆向方法反轉 Colormaps

它還建立了一個散點圖,其 y 值被對映到反向的 viridis colormap 上。reversed() 方法將應用該方法的 colormap 物件反轉。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap

x = np.arange(9)
y = [9, 2, 8, 4, 5, 7, 6, 8, 7]

initial_cmap = cm.get_cmap("viridis")
reversed_cmap = ListedColormap(initial_cmap.colors[::-1])

plt.scatter(x, y, c=y, cmap=reversed_cmap)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot with Inverse Virdis colormap")
plt.colorbar()
plt.show()

輸出:

在 Matplotlib Python 中通過反轉顏色列表來反轉 colormaps

它還建立了一個散點圖,其 y 值被對映到反轉的 viridis colormap 上。任何 colormap 都只是一個顏色列表。我們可以使用 cmap. colors 訪問 colormap cmap 的顏色列表。然後我們將列表反轉,最後使用 matplotlib.cols 包中的 ListedColormap() 函式將反轉後的列表轉換回顏色圖。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn