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

如何用Python Plotly制作自定义配色的固定热图表格

解决方案

可直接通过Plotly的Heatmap组件实现你要的效果,核心是配置离散分段色阶、坐标轴参数,完整可运行代码如下:

import plotly.graph_objects as go
import pandas as pd
import numpy as np

# 数据和你原有代码保持一致
Index = ['1', '2', '3', '4', '5']
Cols = ['A', 'B', 'C', 'D', 'E']
data = [[0, 0, 1, 1, 2],
        [0, 1, 2, 2, 3],
        [1, 2, 2, 3, 4],
        [1, 2, 3, 4, 4],
        [2, 3, 4, 4, 4]]

# 自定义离散分段色阶,完全匹配你要的颜色区间
custom_colorscale = [
    [0, 'darkgreen'],   # 0-1区间
    [0.2, 'darkgreen'],
    [0.2, 'lightgreen'],# 1-2区间
    [0.4, 'lightgreen'],
    [0.4, 'yellow'],    # 2-3区间
    [0.6, 'yellow'],
    [0.6, 'orange'],    # 3-4区间
    [0.8, 'orange'],
    [0.8, 'red'],       #4-5区间
    [1, 'red']
]

# 构建热图
fig = go.Figure(data=go.Heatmap(
    z=data,
    x=Cols,
    y=Index,
    colorscale=custom_colorscale,
    zmin=0,
    zmax=5,
    # 色条配置和你原有效果一致
    colorbar=dict(
        tickvals=[0,1,2,3,4,5],
        ticktext=['0','1','2','3','4','5']
    )
))

# 调整坐标轴和边距,匹配matplotlib输出的布局
fig.update_layout(
    yaxis=dict(autorange='reversed'), # 反转y轴,和原效果顺序一致
    margin=dict(l=20, r=20, t=20, b=20)
)

fig.show()

作为背景使用的方法

如果你要把该热图作为其他图表的背景,只需要先在Figure中添加上述Heatmap轨迹,再添加你原有图表的轨迹即可,Plotly默认按添加顺序层叠,先添加的内容会在底层,如有需要也可以给热图设置opacity参数调整透明度。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 02:36:04