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

雷达图报错:x与y维度不匹配,如何绘制双数据集雷达图?

雷达图绘制错误修复:x与y维度不匹配问题

问题详情

执行代码中ax.fill(angles, scores_interests, 'r', alpha=0.1)语句时触发错误:

x and y must have same first dimension, but have shapes (6,) and (5,)

需求为绘制可同时展示skills和interests两组分数的雷达图,原代码如下:

import matplotlib.pyplot as plt
import numpy as np

# Score values for skills and interests
skills = {
    'Statistics': 5,
    'Python': 5,
    'SQL': 5,
    'QLIK': 5,
    'Pipelines': 5
}

interests = {
    'Statistics': 5,
    'Python': 5,
    'SQL': 5,
    'QLIK': 5,
    'Pipelines': 5
}

# Skill and interest categories
categories = list(skills.keys())

# Scores for the two sets
scores_skills = list(skills.values())
scores_interests = list(interests.values())

# Number of categories
num_categories = len(categories)

# Create angles for the radar chart
angles = np.linspace(0, 2 * np.pi, num_categories, endpoint=False).tolist()
angles += angles[:1]  # To close the radar chart

# Plot the radar chart
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, polar=True)

# Plot the skill scores
ax.fill(angles, scores_skills, 'b', alpha=0.1)
ax.set_thetagrids(np.degrees(angles), labels=categories)
plt.title('Radar Chart - Skills vs. Interests')

# Plot the interest scores
ax.fill(angles, scores_interests, 'r', alpha=0.1)

# Add a legend
plt.legend(['Skills', 'Interests'], loc='upper right')

plt.show()

错误原因

代码中为了闭合雷达图,对angles执行了angles += angles[:1],将其长度从5(对应5个分类)扩展到6,但scores_skills和scores_interests仍为5个元素的列表,导致fill函数的x轴数据(angles)与y轴数据(分数列表)维度不匹配,触发报错。

修复方案

对两组分数列表做相同的闭合处理,在末尾添加各自的第一个元素,使它们的长度与angles保持一致。

修复后的完整代码

import matplotlib.pyplot as plt
import numpy as np

# 技能与兴趣分数
skills = {
    '统计学': 5,
    'Python': 5,
    'SQL': 5,
    'QLIK': 5,
    '数据管道': 5
}

interests = {
    '统计学': 5,
    'Python': 5,
    'SQL': 5,
    'QLIK': 5,
    '数据管道': 5
}

# 分类列表
categories = list(skills.keys())

# 提取分数并闭合列表,匹配angles长度
scores_skills = list(skills.values())
scores_interests = list(interests.values())
scores_skills += scores_skills[:1]
scores_interests += scores_interests[:1]

# 生成雷达图角度
num_categories = len(categories)
angles = np.linspace(0, 2 * np.pi, num_categories, endpoint=False).tolist()
angles += angles[:1]  # 闭合雷达图

# 绘制雷达图
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, polar=True)

# 绘制技能分数区域与折线
ax.fill(angles, scores_skills, 'b', alpha=0.1)
ax.plot(angles, scores_skills, 'b', linewidth=2)

# 绘制兴趣分数区域与折线
ax.fill(angles, scores_interests, 'r', alpha=0.1)
ax.plot(angles, scores_interests, 'r', linewidth=2)

# 设置标签与标题
ax.set_thetagrids(np.degrees(angles), labels=categories)
plt.title('雷达图 - 技能 vs 兴趣')

# 添加图例
plt.legend(['技能', '兴趣'], loc='upper right')

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:13:13