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

如何根据列值为雷达图的外环(类环形图)着色

实现雷达图+环形图结合,外环按Type列着色

原始数据

data = {'Letter': ['A', 'B', 'C', 'D', 'E'],
        'Type': ['Apples', 'Apples', 'Oranges', 'Oranges', 'Bananas'],
        'Value': [1, 2, 0, 5, 6]}

df = pd.DataFrame(data)

你尝试的代码

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

data = {'Letter': ['A', 'B', 'C', 'D', 'E'],
        'Type': ['Apples', 'Apples', 'Oranges', 'Oranges', 'Bananas'],
        'Value': [1, 2, 0, 5, 6]}

df = pd.DataFrame(data)


num_categories = len(df)


angles = np.linspace(0, 2 * np.pi, num_categories, endpoint=False).tolist()


values = df['Value'].tolist()
values += values[:1]
angles += angles[:1]


plt.figure(figsize=(8, 8))
plt.polar(angles, values, marker='o', linestyle='-', linewidth=2)


plt.fill(angles, values, alpha=0.25)

plt.xticks(angles[:-1], df['Letter'])


types = df['Type'].unique()
color_map = {t: i / len(types) for i, t in enumerate(types)}

colors = df['Type'].map(color_map)
plt.fill(angles, values, color=plt.cm.viridis(colors), alpha=0.25)

plt.show()

实现目标效果的代码

要达成你想要的「雷达图外环按Type分组着色」的效果,需要在雷达图外层绘制分段环形(用极坐标条形图实现),再叠加雷达图内容。以下是完整实现代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 加载数据
data = {'Letter': ['A', 'B', 'C', 'D', 'E'],
        'Type': ['Apples', 'Apples', 'Oranges', 'Oranges', 'Bananas'],
        'Value': [1, 2, 0, 5, 6]}
df = pd.DataFrame(data)

num_cats = len(df)
angles = np.linspace(0, 2 * np.pi, num_cats, endpoint=False)
angle_width = 2 * np.pi / num_cats  # 每个类别对应的角度宽度

# 给每个Type分配专属颜色(也可以用colormap自动生成)
type_color_map = {
    'Apples': '#ff6b6b',
    'Oranges': '#ffd93d',
    'Bananas': '#6bcb77'
}
df['color'] = df['Type'].map(type_color_map)

# 创建极坐标画布
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw={'projection': 'polar'})

# 绘制外层环形分段
max_val = df['Value'].max()
inner_r = max_val * 1.1  # 环形内半径
outer_r = inner_r * 1.3  # 环形外半径
for idx in range(num_cats):
    ax.bar(angles[idx], outer_r - inner_r,
           width=angle_width, bottom=inner_r,
           color=df['color'][idx], edgecolor='white', zorder=1)

# 绘制雷达图
values_closed = df['Value'].tolist() + [df['Value'].iloc[0]]
angles_closed = np.concatenate((angles, [angles[0]]))
ax.plot(angles_closed, values_closed, marker='o', linestyle='-', linewidth=2, color='#2d50a1', zorder=2)
ax.fill(angles_closed, values_closed, color='#2d50a1', alpha=0.25, zorder=2)

# 调整图表样式
ax.set_xticks(angles)
ax.set_xticklabels(df['Letter'], fontsize=12)
ax.set_yticklabels([])  # 隐藏径向刻度标签
ax.set_ylim(0, outer_r)

plt.show()

关键说明

  • 外层环形通过ax.bar在极坐标下绘制,每个类别对应一个条形,宽度为角度间隔,高度为内外半径的差值
  • 颜色映射可以手动指定,也可以用plt.cm.get_cmap()自动生成一组颜色
  • 雷达图部分保持闭合绘制,通过zorder参数确保雷达图显示在环形上方
  • 调整径向范围和隐藏多余刻度,让图表更贴合目标样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:52:51