从 RGB 颜色列表创建 python 颜色映射

Creating a color map in python from a list of RGB colors

我想在 python 中创建类似于此图像的彩色地图:

但我的地图只有 3 行 4 列。我想使用 RGB 值为每个正方形分配一个特定的颜色值。我试过这段代码

colors=np.array([[0.01, 0.08, 0.01], [0.01, 0.16, 0.01], [0.01, 0.165, 0.01], [0.01, 0.3, 0.01],
                 [0.01, 0.2, 0.01], [0.666, 0.333, 0.01], [0.01, 0.165, 0.01], [0.01, 0.3, 0.01],
                 [0.01, 0.2, 0.01], [0.666, 0.333, 0.01], [0.01, 0.165, 0.01], [0.01, 0.3, 0.01]])


fig, ax=plt.subplots()
ax.imshow(colors)
ax.set_aspect('equal')
plt.show()

但输出结果与我的预期不符。似乎用这种方法我不能使用 RGB 值来表示正方形的颜色。任何人都可以帮助我吗?谢谢!

您有一个 (12,3) 颜色数组,而您需要一个 (4, 3, 3) 图像,每个像素一种 RGB 颜色。

import numpy as np  # type: ignore
import matplotlib.pyplot as plt  # type: ignore

colors = np.array(
    [
        # this is the first row
        [
            # these are the 3 pixels in the first row
            [0.01, 0.08, 0.01],
            [0.01, 0.16, 0.01],
            [0.01, 0.165, 0.01],
        ],
        [
            [0.01, 0.3, 0.01],
            [0.01, 0.2, 0.01],
            [0.666, 0.333, 0.01],
        ],
        [
            [0.01, 0.165, 0.01],
            [0.01, 0.3, 0.01],
            [0.01, 0.2, 0.01],
        ],
        # this is the fourth row
        [
            [0.666, 0.333, 0.01],
            [0.01, 0.165, 0.01],
            [0.01, 0.3, 0.01],
        ],
    ]
)
print(colors.shape)


fig, ax = plt.subplots()
ax.imshow(colors)
ax.set_aspect("equal")
plt.show()

根据需要重新排列 rows/columns 中的数据。