将值映射到matplotlib中的颜色 [英] Map values to colors in matplotlib

查看:119
本文介绍了将值映射到matplotlib中的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表,如下所示:

I have a list of numbers as follows:

lst = [1.9378076554115014, 1.2084586588892861, 1.2133096565896173, 
       1.2427632053442292, 1.1809971732733273, 0.91960143581348919, 
       1.1106310149587162, 1.1106310149587162, 1.1527004351293346, 
       0.87318084435885079, 1.1666132876686799, 1.1666132876686799]

我想将这些数字转换为颜色以显示. 我想要灰度,但是当我按原样使用这些数字时,它给了我一个错误:

I want to convert these numbers to colors for display. I want gray scale but when I am using these numbers as it is, it gives me an error:

ValueError: to_rgba: Invalid rgba arg "1.35252299785"
to_rgb: Invalid rgb arg "1.35252299785"
gray (string) must be in range 0-1 

...据我了解是因为它超过了1.

...which I understand is due to it exceeding 1.

接下来,我尝试将列表中编号最高的项划分为小于1的值.但这会产生非常窄的色阶,而值之间几乎没有任何区别.

I next tried to divide the items in the list with the highest number in the list to give values less than 1. But this gives a very narrow color scale with hardly any difference between values.

有什么方法可以给颜色指定最小和最大范围,并将这些值转换为颜色?我正在使用matplotlib.

Is there any way in which I can give some min and max range to colors and convert these values to color? I am using matplotlib.

推荐答案

您正在寻找matplotlib.colors模块.这提供了许多类,可以从值映射到颜色图值.

The matplotlib.colors module is what you are looking for. This provides a number of classes to map from values to colourmap values.

import matplotlib
import matplotlib.cm as cm

lst = [1.9378076554115014, 1.2084586588892861, 1.2133096565896173, 1.2427632053442292, 
       1.1809971732733273, 0.91960143581348919, 1.1106310149587162, 1.1106310149587162, 
       1.1527004351293346, 0.87318084435885079, 1.1666132876686799, 1.1666132876686799]

minima = min(lst)
maxima = max(lst)

norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.Greys_r)

for v in lst:
    print(mapper.to_rgba(v))

一般方法是在数据中找到minimamaxima.使用这些来创建Normalize实例(其他规范化类也可用,例如对数刻度).接下来,使用Normalize实例和所选的 colormap 创建一个ScalarMappable.然后,您可以使用mapper.to_rgba(v)通过归一化比例将输入值v映射到目标颜色.

The general approach is find the minima and maxima in your data. Use these to create a Normalize instance (other normalisation classes are available, e.g. log scale). Next you create a ScalarMappable using the Normalize instance and your chosen colormap. You can then use mapper.to_rgba(v) to map from an input value v, via your normalised scale, to a target color.

for v in sorted(lst):
    print("%.4f: %.4f" % (v, mapper.to_rgba(v)[0]) )

产生输出:

0.8732: 0.0000
0.9196: 0.0501
1.1106: 0.2842
1.1106: 0.2842
1.1527: 0.3348
1.1666: 0.3469
1.1666: 0.3469
1.1810: 0.3632
1.2085: 0.3875
1.2133: 0.3916
1.2428: 0.4200
1.9378: 1.0000

matplotlib.colors 模块文档中提供了更多信息(如果需要).

The matplotlib.colors module documentation has more information if needed.

这篇关于将值映射到matplotlib中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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