创建 matplotlib PolyCollection 颜色映射,将每个单元格映射到一种颜色

Create matplotlib PolyCollection colormap mapping each cell to a color

我正在尝试使用 matplotlib PolyCollection 绘制 3D 图形的 2D 切片,但我想为每个单元格设置不同的颜色。有没有一种方法可以轻松创建颜色图来完成此操作?

我有一组正在绘制的顶点,然后使用 array 参数在这些顶点内放置一个二维数组。我还有一个二维列表,其中包含每个单元格的 RGB 值。我如何从这个 2D RGB 列表生成颜色图以与 PolyCollection 配对?

例如:

import numpy
x = numpy.arange(4).reshape(2,2)
colors = [[(.2, .2, .3), (0, 0, 0)], [(.5, .5, .5), (.6, .3, .8)]]

我希望位于 (0, 0) 的单元格为 (.2, .2, .3) 并且 (0, 1) 为 (0, 0, 0)。

我想我需要 Normalize 的某种组合 实例和一个 ListedColormap.

或者,有没有办法将一组 RGB 值传递给 PolyCollection 作为 array 参数,因此每个 'value' 只是颜色 细胞的?

如果你有一个二维颜色序列,你可以使用 facecolors kwarg(或者等效的 collection.set_facecolors(rgb_seq).

但是,如果您通过 ax.pcolor 制作了 PolyCollection 或以其他方式称为 collection.set_array(some_data),则需要通过以下方式禁用标量颜色映射行为调用 collection.set_array(None).

举个例子:

import numpy as np
import matplotlib.pyplot as plt

rgb = np.random.random((100, 3))

fig, ax = plt.subplots()
coll = ax.pcolor(np.zeros((10, 10)))

# If we left out the "array=None", the colors would still be controlled by the
# values of the array we passed in, and the "facecolors" kwarg would be
# ignored. This is equivalent to calling `coll.set_array(None)` and then
# `coll.set_facecolors(rgb)`.
coll.set(array=None, facecolors=rgb)

plt.show()