检索Matplotlib热图颜色 [英] Retrieving Matplotlib Heatmap Colors
问题描述
我正在尝试检索由imshow()
函数生成的matplotlib热图上每个单元格的颜色,例如由以下magic_function
执行的操作:
I am trying to retrieve the colors of each cell on a matplotlib heatmap, generated by the imshow()
function, such as performed by the magic_function
below:
import matplotlib.pyplot as plt
import numpy as np
hm = plt.imshow(np.random.rand(10, 10))
color_matrix = hm.magic_function() #returns matrix containing the RGB/Hex values of each cell
推荐答案
您正在寻找通过imshow
创建的图像所使用的色图.现在,当然,您可以像其他答案所建议的那样,逆向工程该颜色图如何首先进入图像.这似乎很麻烦,而且通常甚至不可能.
You are looking for the colormap that is used by the image created via imshow
. Now of course you can reverse engineer how that colormap got into the image in the first place like the other answer suggests. That seems cumbersome and often enough isn't even possible.
因此,给定一个AxesImage
(由ScalarMappable
而言,您可以通过.cmap
使用该色图.由于数据值已归一化到0..1之间的范围,因此需要归一化,该归一化是从.norm
属性获得的.最后,您需要从.get_array()
方法获得的数据.
So given an AxesImage
(the object returned by imshow
) or for that matter any other ScalarMappable
, you get the colormap in use via .cmap
. Since the data values are normalized to the range between 0..1, you need a normalization, which you get from the .norm
attribute. Finally, you need the data, which you get from the .get_array()
method.
magic_function
因此是由三个功能组成的链.
The magic_function
is hence a chain of three functions.
im = plt.imshow(np.random.rand(10, 10))
color_matrix = im.cmap(im.norm(im.get_array()))
color_matrix
现在是与图像中像素相对应的(10、10、4)形状的RGBA颜色数组.
color_matrix
is now the (10, 10, 4)-shaped RGBA array of colors corresponding to the pixels in the image.
这篇关于检索Matplotlib热图颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!