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

如何在Plotly sunburst旭日图最外层外侧自动标注各分段对应数值

Plotly旭日图最外层外侧自动添加数值标注解决方案

以下是完全自动化的实现方案,无需硬编码任何节点或数值信息,可适配任意数量的外层分段:

完整可运行代码

import plotly.express as px
import numpy as np

# 原有旭日图生成逻辑
df = px.data.tips()
fig = px.sunburst(df, path=['day', 'time', 'sex'], values='total_bill')

# 自动化标注处理逻辑
sunburst_data = fig.data[0]
path_level_count = len(sunburst_data.path)
# 自动筛选最外层节点:节点ID的斜杠数量等于路径层级减1即为最外层
outer_node_mask = [node_id.count('/') == path_level_count - 1 for node_id in sunburst_data.ids]

# 提取最外层节点的数值、角度参数
outer_values = sunburst_data.values[outer_node_mask]
outer_start_angles = sunburst_data.startangles[outer_node_mask]
outer_delta_angles = sunburst_data.deltaangles[outer_node_mask]

# 标注距离旭日图外圈的距离,可按需调整
annotation_radius = 1.15
annotations = []

for val, start_angle, delta_angle in zip(outer_values, outer_start_angles, outer_delta_angles):
    # 计算分段中心角度
    mid_angle = start_angle + delta_angle / 2
    # 角度转弧度后计算标注的直角坐标
    mid_angle_rad = np.deg2rad(mid_angle)
    x = annotation_radius * np.cos(mid_angle_rad)
    y = annotation_radius * np.sin(mid_angle_rad)
    # 调整文本角度避免倒置
    text_angle = mid_angle if mid_angle < 180 else mid_angle + 180
    
    annotations.append({
        "x": x, "y": y,
        "text": f"{val:.1f}", # 数值格式化规则可自行修改
        "showarrow": False,
        "textangle": text_angle,
        "font": {"size": 10, "color": "#000"}
    })

# 应用标注并调整边距避免标注被截断
fig.update_layout(
    annotations=annotations,
    margin=dict(l=80, r=80, t=80, b=80)
)

fig.show()

核心逻辑说明

  • 自动识别最外层节点:Plotly生成的旭日图所有节点ID采用父层级/子层级的拼接格式,通过统计斜杠数量即可自动筛选最外层节点,适配任意层级的路径配置。
  • 自动获取位置参数:无需手动计算分段位置,直接调用sunburst内置的startangles(分段起始角度)和deltaangles(分段扫过角度)属性即可定位每个分段的中心。
  • 自适应大量分段:就算外层有数百个分段,代码也会自动遍历生成标注,仅需根据实际显示效果调整标注半径、字体大小、页面边距等样式参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:09