计算一系列值的 RGB 值以创建热图 [英] Calculate RGB value for a range of values to create heat map

查看:25
本文介绍了计算一系列值的 RGB 值以创建热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 创建热图.为此,我必须为可能值范围内的每个值分配一个 RGB 值.我想将颜色从蓝色(最小值)更改为绿色到红色(最大值).

I am trying to create a heat map with python. For this I have to assign an RGB value to every value in the range of possible values. I thought of changing the color from blue (minimal value) over green to red (maximal value).

下面的图片示例解释了我对颜色组合的看法:我们有一个范围从 1(纯蓝色)到 3(纯红色),2 介于两者之间,类似于绿色.

The picture example below explains how I thought of the color composition: We have a range from 1 (pure blue) to 3 (pure red), 2 is in between resembled by green.

我阅读了线性插值并编写了一个函数,该函数(或多或少)处理最小值和最大值之间范围内某个值的计算,并返回一个 RGB 元组.它使用 ifelif 条件(这并不让我完全满意):

I read about linear interpolation and wrote a function that (more or less) handles the calculation for a certain value in the range between a minimum and a maximum and returns an RGB tuple. It uses if and elif conditions (which does not make me completely happy):

def convert_to_rgb(minimum, maximum, value):
    minimum, maximum = float(minimum), float(maximum)    
    halfmax = (minimum + maximum) / 2
    if minimum <= value <= halfmax:
        r = 0
        g = int( 255./(halfmax - minimum) * (value - minimum))
        b = int( 255. + -255./(halfmax - minimum)  * (value - minimum))
        return (r,g,b)    
    elif halfmax < value <= maximum:
        r = int( 255./(maximum - halfmax) * (value - halfmax))
        g = int( 255. + -255./(maximum - halfmax)  * (value - halfmax))
        b = 0
        return (r,g,b)

但是我想知道是否可以为每个颜色值编写一个函数而无需使用 if 条件.有人有想法吗?非常感谢!

However I wonder if one could write a function for each color value without using if conditions. Does anybody have an idea? Thank you a lot!

推荐答案

def rgb(minimum, maximum, value):
    minimum, maximum = float(minimum), float(maximum)
    ratio = 2 * (value-minimum) / (maximum - minimum)
    b = int(max(0, 255*(1 - ratio)))
    r = int(max(0, 255*(ratio - 1)))
    g = 255 - b - r
    return r, g, b

这篇关于计算一系列值的 RGB 值以创建热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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