检索Matplotlib热图颜色 [英] Retrieving Matplotlib Heatmap Colors

查看:105
本文介绍了检索Matplotlib热图颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索由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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆