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

自定义标签的Treemap仅显示标签与计数问题求助

Plotly Treemap标签显示问题修复方案

问题根源

你的代码未指定values参数,Plotly无法识别要显示的“计数”对应哪个字段;同时多余的color_continuous_midpoint参数(与离散颜色序列冲突)可能干扰渲染逻辑,导致textinfo='label+value'无法按预期显示内容。

修复步骤及代码

情况1:已有计数字段(比如代码里的commits)

直接指定values为计数字段即可:

import plotly.express as px
import numpy as np

fig = px.treemap(
    api_history,
    path=['Version'],
    values='commits',  # 指定计数字段,让textinfo的value对应计数
    color='Version',
    color_discrete_sequence=px.colors.qualitative.Pastel,
    width=1000,
    height=800,
    title='Visualization of all extracted API Version Identifiers',
    hover_data=['Version', 'commits']  # hover时显示版本和计数
)

fig.update_traces(textinfo='label+value')
fig.update_layout(
    margin=dict(t=50, l=25, r=25, b=25),
    template='ggplot2',
    hoverlabel=dict(font_size=16, font_family="PT Sans"),
    font=dict(size=20, family='PT Sans'),
    paper_bgcolor='rgba(233,233,233,100)'
)
fig.show()

情况2:无现成计数字段,需要统计Version出现次数

先预处理数据统计次数,再绘制:

import plotly.express as px
import numpy as np

# 统计每个Version的出现次数
api_history_counts = api_history['Version'].value_counts().reset_index(name='count')
api_history_counts.columns = ['Version', 'count']

fig = px.treemap(
    api_history_counts,
    path=['Version'],
    values='count',  # 使用统计后的计数字段
    color='Version',
    color_discrete_sequence=px.colors.qualitative.Pastel,
    width=1000,
    height=800,
    title='Visualization of all extracted API Version Identifiers',
    hover_data=['Version', 'count']
)

fig.update_traces(textinfo='label+value')
fig.update_layout(
    margin=dict(t=50, l=25, r=25, b=25),
    template='ggplot2',
    hoverlabel=dict(font_size=16, font_family="PT Sans"),
    font=dict(size=20, family='PT Sans'),
    paper_bgcolor='rgba(233,233,233,100)'
)
fig.show()

关键修改说明

  • 添加values参数:明确告诉Plotly每个节点的数值(即你要显示的计数),这样textinfo='label+value'里的value才会正确展示对应计数
  • 移除color_continuous_midpoint:该参数用于连续颜色映射,和你用的离散颜色序列冲突,属于无效配置,移除后避免潜在问题
  • 调整hover_data:按需添加计数字段,让hover时也能看到完整信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:40:24