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

如何为Plotly极坐标图按类别设置不同背景色

为Plotly极坐标雷达图添加分类背景色

可以实现按技能分类给极坐标图添加不同背景色的效果,核心思路是为每个分类对应的扇形区域绘制填充背景,再将技能雷达图叠加在上方。以下是修改后的完整代码:

import plotly.graph_objects as go

# 保留分类前缀用于分组
categories_with_prefix = [
    "[lang] English", "[lang] Spanish", "[lang] German",
    "[dev] JS", "[dev] Python", "[dev] Go", "[dev] C#",
    "[skill] leadership", "[skill] creativity"
]

# 按分类整理技能标签
category_groups = {}
for item in categories_with_prefix:
    cat, name = item.split("] ")
    cat = cat.strip("[")
    if cat not in category_groups:
        category_groups[cat] = []
    category_groups[cat].append(name)

# 生成最终的技能标签列表
categories = [name for group in category_groups.values() for name in group]

# 技能评分数据
ratings = {
    "Alice": [4,5,0,3,4,5,2,3,5],
    "Bob":   [3,1,4,2,3,1,1,3,2],
}

# 定义每个分类的背景色(可按需调整)
group_colors = {
    "lang": "#e6f7ff",
    "dev": "#fff2e6",
    "skill": "#f9f0ff"
}

# 计算每个分类在极坐标中的起始和结束索引
group_indices = {}
current_idx = 0
for cat, items in category_groups.items():
    group_indices[cat] = (current_idx, current_idx + len(items) - 1)
    current_idx += len(items)

fig = go.Figure()

max_rating = 5  # 评分最大值,对应背景的最大半径
# 绘制各分类的背景扇形
for cat, (start_idx, end_idx) in group_indices.items():
    # 构建背景的theta序列,包含闭合点
    theta_bg = categories[start_idx:end_idx+1] + [categories[start_idx]]
    # 背景的半径全部设为最大评分值
    r_bg = [max_rating] * len(theta_bg)
    
    fig.add_trace(go.Scatterpolar(
        r=r_bg,
        theta=theta_bg,
        fill='toself',
        fillcolor=group_colors[cat],
        line=dict(color='rgba(0,0,0,0)'),  # 隐藏背景边框
        showlegend=False,
        hoverinfo='skip'  # 关闭背景的hover提示
    ))

# 添加Alice和Bob的技能雷达图
for name in ratings.keys():
    fig.add_trace(go.Scatterpolar(
        r=ratings[name] + [ratings[name][0]],
        theta=categories + [categories[0]],
        name=name,
    ))

# 调整布局
fig.update_layout(
    polar=dict(
        radialaxis=dict(
            visible=True,
            range=[0, max_rating]
        ),
        angularaxis=dict(
            direction="clockwise"
        )
    ),
    showlegend=True
)

fig.show()

关键说明:

  • 保留了原始的分类前缀信息,用于精准划分每个技能所属的类别范围
  • 为每个分类自定义了背景色,你可以根据需求替换成任意颜色代码
  • 背景扇形通过Scatterpolar绘制,设置fill='toself'实现区域填充,隐藏边框和图例避免干扰数据展示
  • 背景轨迹需要先添加,确保技能雷达图能叠加在背景之上

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:05:27