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

绘图时如何为DataFrame中的数值分配对应的自定义RGB颜色

实现方案

步骤1:将DataFrame数值映射为RGB颜色矩阵

首先需要把原始DataFrame里的每个值,通过你的颜色映射字典转成matplotlib支持的RGB格式,注意matplotlib要求RGB通道值为0-1范围的浮点数,如果你现有字典的RGB是0-255范围,需要先对每个通道除以255做转换。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 示例:替换为你自己的DataFrame
df = pd.DataFrame([
    [1,2,3],
    [2,3,1],
    [3,1,2]
])
# 示例:替换为你自己的颜色映射字典,key为df中的值,value为RGB元组
color_map = {
    1: (1, 0, 0), # 红色
    2: (0, 1, 0), # 绿色
    3: (0, 0, 1)  # 蓝色
}

# 小数据量场景:直接用applymap生成颜色矩阵
color_matrix = np.array(df.applymap(lambda x: color_map[x]).tolist())

# 大数据量场景:用numpy向量化操作提升性能
# vec_map = np.vectorize(lambda x: color_map[x])
# r, g, b = vec_map(df.values)
# color_matrix = np.dstack((r,g,b))

步骤2:按位置渲染颜色

场景1:直接渲染矩阵(基础需求)

用imshow直接读取RGB颜色矩阵渲染即可,坐标自动对应DataFrame的行列位置:

plt.figure(figsize=(6,6))
# interpolation设为nearest避免边缘模糊
plt.imshow(color_matrix, interpolation='nearest')
# 可选:配置行列刻度为原始DataFrame的行列名
plt.xticks(ticks=np.arange(len(df.columns)), labels=df.columns)
plt.yticks(ticks=np.arange(len(df.index)), labels=df.index)
# 可选:在每个位置标注原始数值
for i in range(len(df.index)):
    for j in range(len(df.columns)):
        plt.text(j, i, df.iloc[i,j], ha='center', va='center', color='white', fontsize=12)
plt.show()

场景2:结合seaborn热力图使用(需额外样式/统计配置)

如果需要保留seaborn热力图的其他功能,可将自定义颜色映射转为Colormap传入:

import seaborn as sns
from matplotlib.colors import ListedColormap

# 按数值从小到大排序生成自定义色盘
sorted_values = sorted(color_map.keys())
custom_cmap = ListedColormap([color_map[v] for v in sorted_values])

plt.figure(figsize=(6,6))
# cbar设为False关闭不需要的色条,annot=True可展示原始数值
sns.heatmap(df, cmap=custom_cmap, cbar=False, annot=True, fmt='d')
plt.show()

注意事项

  • 若存在DataFrame中的值未在颜色字典中定义的情况,可在映射逻辑中添加缺省值,比如lambda x: color_map.get(x, (1,1,1)),缺省值为白色
  • 0-255范围的RGB值必须先转为0-1浮点数,否则会触发渲染报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:09:04