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

Matplotlib箱线图报错:ValueError: 标签与X维度不兼容

解决Matplotlib箱线图的"Dimensions of labels and X must be compatible"错误

你遇到的问题核心是matplotlib的boxplot函数对输入数据的格式要求:

  • 你传入的df['population_density']是一维数组,matplotlib会默认将其视为单个数据集,只会绘制1个箱线图
  • 但你传入了6个标签,标签数量(6)和数据集数量(1)不匹配,因此触发维度不兼容的错误

虽然你有6个数据点,但每个数据点属于不同分组,需要让boxplot识别出这是6个独立的分组,每个分组对应一个数据集(哪怕每个数据集只有1个值)。

方案1:手动整理数据为二维数组

把每个大洲的密度值包装成单独的列表,形成二维数组,这样boxplot会识别出6个独立的数据集,和6个标签一一对应:

import pandas as pd
import matplotlib.pyplot as plt

data = {'continent': ['Asia', 'Africa', 'Europe', 'North America', 'South America', 'Australia'],
       'population_density': [150, 44, 72, 22, 25, 3]}
df = pd.DataFrame(data)

# 将每个密度值转为单元素列表,构造二维数组
grouped_data = [[val] for val in df['population_density']]
plt.boxplot(grouped_data, labels=df['continent'])
plt.title('Population Densities by Continent')
plt.ylabel('Population Density')
plt.show()

方案2:使用Pandas内置的箱线图方法

Pandas的boxplot方法更适合处理带分组的数据,直接指定分组列和数值列即可,无需手动整理数据:

import pandas as pd
import matplotlib.pyplot as plt

data = {'continent': ['Asia', 'Africa', 'Europe', 'North America', 'South America', 'Australia'],
       'population_density': [150, 44, 72, 22, 25, 3]}
df = pd.DataFrame(data)

# 按continent分组绘制population_density的箱线图
df.boxplot(column='population_density', by='continent')
plt.title('Population Densities by Continent')
plt.suptitle('')  # 移除Pandas自动添加的顶部标题
plt.ylabel('Population Density')
plt.show()

内容的提问来源于stack exchange,提问作者Çağrı Çelik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:22:27