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

如何将Plotly热力图(华夫图样式)图例替换为文本标签?

解决Plotly热力图(华夫图)颜色条数值替换为文本标签的问题

要实现将热力图颜色条的数值替换为对应文本,只需完成两个核心修改:填充自定义悬停数据和配置颜色条刻度文本,以下是具体方案:

关键修改点

  • 填充customdata:将空的自定义数据数组替换为z值对应的文本描述,确保悬停提示显示文本而非原始数值。
  • 配置颜色条刻度:在热力图轨迹中指定colorbar的tickvals(对应z的原始数值)和ticktext(对应文本标签),让颜色条直接显示文本。

修改后的完整代码

import numpy as np
import plotly.graph_objects as go

m= 10
n= 10
z = np.ones((m, n))
z[2:, 6] = 2
z[:4, 7] = 2
z[4:, 7] = 3
z[:4, 8] = 3
z[4:, 8] = 4
z[:5, 9] = 5
z[5:, 9] = 6

# 数值到文本的映射字典
d = {1: "Insufficient data",
    2: "Moderate distance to target",
    3: "Close to target",
    4: "Far from target",
    5: "Very far from target",
    6: "Target met or almost met",
    }

# 批量将z数组的数值转换为对应文本,填充customdata
customdata = np.vectorize(d.get)(z)

colorscale = [[0, "#adb5bd"],
              [0.16, "#adb5bd"],
              [0.16, "#ffc107"],
              [0.33,  "#ffc107"],
              [0.33,  "#28a745"],
              [0.5,  "#28a745"],
              [0.5,  "#d76406"],
              [0.66,  "#d76406"],
              [0.66,  "#dc3545"],
              [0.83, "#dc3545" ],
              [0.83, "#007bff" ],
              [1, "#007bff"]]

ticktext = ["Insufficient data", "Moderate distance to target", "Close to target", "Far from target", "Very far from target","Target met or almost met"]
xlabels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
ylabels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

fig = go.Figure(go.Heatmap(x=xlabels, y = ylabels, z=z,
                           customdata=customdata, xgap=3, ygap=3,
                           colorscale=colorscale, showscale=True,
                           hovertemplate="(%{y}, %{x}): %{customdata}<extra></extra>"))
fig.update_layout(margin=dict(l=40, r=20, t=20, b=40),yaxis_autorange='reversed')
fig.update_yaxes(showticklabels=False)
fig.update_xaxes(showticklabels=False)
# 配置颜色条,替换数值为文本
fig.update_traces(
    colorbar_orientation='h',
    colorbar=dict(
        tickmode='array',
        tickvals=[1,2,3,4,5,6],  # 绑定z的原始数值
        ticktext=ticktext         # 绑定要显示的文本标签
    ),
    selector=dict(type='heatmap')
)

fig.show()

代码说明

  1. customdata填充:用np.vectorize(d.get)(z)快速批量转换z数组的所有数值为字典中对应的文本,保证悬停提示显示正确描述。
  2. 颜色条配置:通过tickmode='array'指定自定义刻度规则,tickvals关联z的原始数值,ticktext关联对应文本,实现颜色条的文本替换。
  3. 保留原有华夫图的样式设置(单元格间距、轴标签隐藏等),仅修改数据映射和颜色条显示逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:05:22