You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现数值到绿红渐变RGB颜色的转换?

Python实现数值到红绿渐变RGB颜色的转换

要实现数值对应绿到红的渐变背景色,有两种常用方案:手动实现线性渐变逻辑,或者借助现成的可视化库快速实现。

一、手动实现(无依赖)

直接通过线性插值计算RGB分量,绿对应(0,255,0),红对应(255,0,0),根据当前值在最小值和最大值之间的比例调整红、绿通道的数值:

def num_to_color(min_value, max_value, current_value):
    # 处理边界值:小于最小值返回纯绿,大于最大值返回纯红
    if current_value <= min_value:
        return (0, 255, 0)
    if current_value >= max_value:
        return (255, 0, 0)
    
    # 计算当前值在区间内的归一化比例(0到1之间)
    ratio = (current_value - min_value) / (max_value - min_value)
    
    # 线性插值计算RGB分量,蓝色通道保持为0
    red = int(ratio * 255)
    green = int((1 - ratio) * 255)
    return (red, green, 0)

这个方案轻量简洁,无需额外安装库,适合简单的线性渐变需求。

二、借助Matplotlib库实现

如果需要更灵活的渐变效果(比如非线性渐变、预设色彩映射),可以用Matplotlib的颜色映射功能:

import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

def num_to_color(min_value, max_value, current_value):
    # 创建归一化对象,将数值映射到0-1范围
    norm = Normalize(vmin=min_value, vmax=max_value)
    # 选择绿到红的色彩映射(RdYlGn_r是反转的红黄绿映射,实现绿到红渐变)
    cmap = plt.get_cmap('RdYlGn_r')
    
    # 获取RGBA颜色值,转换为0-255范围的RGB元组
    rgba = cmap(norm(current_value))
    rgb = tuple(int(component * 255) for component in rgba[:3])
    return rgb

Matplotlib提供了大量预设色彩映射,你可以根据需求替换RdYlGn_r为其他映射(比如coolwarm_r),也可以自定义渐变规则。

三、生成带条件格式的Excel表格示例

如果要将颜色应用到Excel表格中,可以结合openpyxl库实现:

from openpyxl import Workbook
from openpyxl.styles import PatternFill

# 复用前面定义的num_to_color函数
def num_to_color(min_value, max_value, current_value):
    if current_value <= min_value:
        return (0, 255, 0)
    if current_value >= max_value:
        return (255, 0, 0)
    ratio = (current_value - min_value) / (max_value - min_value)
    red = int(ratio * 255)
    green = int((1 - ratio) * 255)
    return (red, green, 0)

# 创建工作簿和工作表
wb = Workbook()
ws = wb.active

# 示例数据
data = [
    [15, 30, 45],
    [60, 75, 90],
    [20, 50, 80]
]

# 计算数据的最小值和最大值
min_val = min(min(row) for row in data)
max_val = max(max(row) for row in data)

# 遍历数据,为每个单元格设置背景色
for row_idx, row in enumerate(data, 1):
    for col_idx, value in enumerate(row, 1):
        cell = ws.cell(row=row_idx, column=col_idx, value=value)
        r, g, b = num_to_color(min_val, max_val, value)
        # 转换为Excel支持的十六进制颜色码
        hex_color = f"{r:02X}{g:02X}{b:02X}"
        cell.fill = PatternFill(start_color=hex_color, end_color=hex_color, fill_type="solid")

# 保存文件
wb.save("conditional_formatting_table.xlsx")

内容的提问来源于stack exchange,提问作者Kucherov Egor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:15:35