简体   繁体   English

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

[英]Create matplotlib PolyCollection colormap mapping each cell to a color

I'm trying to plot a 2D slice of a 3D figure with matplotlib PolyCollection , but I want to set a different color for each cell. 我正在尝试使用matplotlib PolyCollection绘制 3D图形的2D切片,但是我想为每个单元格设置不同的颜色。 Is there a way to easily create a colormap to accomplish this? 有没有一种方法可以轻松创建一个颜色图来完成此任务?

I have a set of vertices I'm plotting then using the array argument to put an 2D array inside these vertices. 我要绘制一组顶点,然后使用array参数将2D数组放入这些顶点中。 I also have a 2D list that holds the RGB value for each cell. 我还有一个2D列表,其中包含每个单元的RGB值。 How can I generate a colormap from this 2D RGB list to pair with the PolyCollection? 如何从此2D RGB列表生成色彩图以与PolyCollection配对?

For example: 例如:

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

I want the cell at (0, 0) to be (.2, .2, .3) and (0, 1) to be (0, 0, 0). 我希望位于(0,0)的单元格为(.2,.2,.3)和(0,1)为(0,0,0)。

I'm guessing I need some combination of a Normalize instance and a ListedColormap . 我猜我需要Normalize实例和ListedColormap的某种组合。

Alternatively, is there a way to just pass an array of RGB values to PolyCollection as the array argument so that each 'value' is simply the color of the cell? 或者,是否可以将RGB值array作为array参数传递给PolyCollection,以便每个“值”仅是单元格的颜色?

If you have a sequence of 2D colors, you can use the facecolors kwarg (or equivalently collection.set_facecolors(rgb_seq) . 如果具有2D颜色序列,则可以使用facecolors kwarg(或等效的collection.set_facecolors(rgb_seq)

However, if you've made the PolyCollection through ax.pcolor or otherwise called collection.set_array(some_data) in another way, you'll need to disable the scalar-color-mapping behavior by calling collection.set_array(None) . 但是,如果通过ax.pcolor或以其他方式调用collection.set_array(some_data)制作了PolyCollection ,则需要通过调用collection.set_array(None)来禁用标量颜色映射行为。

As an example: 举个例子:

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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM