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

如何用Plotly创建带文本标签与颜色强度的瓷砖图(含边框)

解决方案:用Plotly Heatmap实现带边框和文本标签的瓷砖图

直接使用plotly.graph_objects.Heatmap可以满足你的需求,它支持设置瓷砖边框、自定义文本标签,且颜色随val字段动态变化。以下是完整实现代码:

import pandas as pd
import plotly.graph_objects as go

# 初始化数据
df = pd.DataFrame({
    'row': ['A','A','A','B','B','B'],
    'col': [1,2,3,1,2,3],
    'val': [0.1,0.9,0.2,0.5,0.2,0.2],
    'animal': ['duck', 'squirrel', 'horse', 'cow', 'pig', 'cat']
})

# 创建瓷砖图
fig = go.Figure(data=go.Heatmap(
    z=df['val'],
    x=df['col'],
    y=df['row'],
    text=df['animal'],  # 瓷砖内显示的文本
    texttemplate='%{text}',  # 渲染文本的模板
    textfont=dict(size=12, color='white'),  # 文本样式
    hoverinfo='text+z',  # 悬浮提示显示文本和val值
    colorscale='Viridis',  # 颜色渐变方案
    marker=dict(
        line=dict(color='black', width=2)  # 设置瓷砖边框
    )
))

# 调整布局
fig.update_layout(
    title='带边框和文本标签的瓷砖图',
    xaxis_title='列',
    yaxis_title='行',
    yaxis=dict(autorange='reversed')  # 让行A显示在上方
)

fig.show()

关键参数说明

  • marker.line:通过color和width设置瓷砖的边框颜色和粗细,解决imshow无法添加边框的问题。
  • text和texttemplate:指定瓷砖内显示的文本内容,并控制渲染格式。
  • colorscale:可选其他配色方案(如'Blues'、'Reds'),根据需求调整颜色渐变方向。
  • yaxis=dict(autorange='reversed'):默认Heatmap的y轴是从下往上排列,反转后让行A显示在顶部,符合常规阅读习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:15:20