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

Matplotlib绘制柱状图时报错:only size-1 arrays can be converted to Python scalars

问题:绘制分类特征与数值特征相关性柱状图时的TypeError解决

我想编写一个函数,接收特征名字符串,返回绘制柱状图的x轴和y轴数据,展示目标特征(如sepal_length)与species分类的相关性。数据集包含species及sepal_length等特征,我的代码如下:

def correlation_group(feature):
  y_axis = df[['species',feature]].groupby('species').mean()
  x_axis= df.species.unique()
  y = []
  for i in range(1) :
      y.append(y_axis[i:])
  print(y)

  return x_axis, y

y = 'sepal_length'
x,y = correlation_group(y)
print(y)
plt.bar(x,y)

运行后出现如下报错:

TypeError                                 Traceback (most recent call last)
<ipython-input-39-cd8e1ad8a982> in <module>
     12 x,y = correlation_group(y)
     13 print(y)
---&gt; 14 plt.bar(x,y)

D:\anaconda3\lib\site-packages\matplotlib\pyplot.py in bar(x, height, width, bottom, align, data, **kwargs)
   2485         x, height, width=0.8, bottom=None, *, align='center',
   2486         data=None, **kwargs):
-&gt; 2487     return gca().bar(
   2488         x, height, width=width, bottom=bottom, align=align,
   2489         **({"data": data} if data is not None else {}), **kwargs)

D:\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1445     def inner(ax, *args, data=None, **kwargs):
   1446         if data is None:
-&gt; 1447             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448 
   1449         bound = new_sig.bind(ax, *args, **kwargs)

D:\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bar(self, x, height, width, bottom, align, **kwargs)
   2479         args = zip(left, bottom, width, height, color, edgecolor, linewidth)
   2480         for l, b, w, h, c, e, lw in args:
-&gt; 2481             r = mpatches.Rectangle(
   2482                 xy=(l, b), width=w, height=h,
   2483                 facecolor=c,

D:\anaconda3\lib\site-packages\matplotlib\patches.py in __init__(self, xy, width, height, angle, **kwargs)
    740         """
    741 
--&gt; 742         Patch.__init__(self, **kwargs)
    743 
    744         self._x0 = xy[0]

D:\anaconda3\lib\site-packages\matplotlib\patches.py in __init__(self, edgecolor, facecolor, color, linewidth, linestyle, antialiased, hatch, fill, capstyle, joinstyle, **kwargs)
     86         self.set_fill(fill)
     87         self.set_linestyle(linestyle)
---&gt; 88         self.set_linewidth(linewidth)
     89         self.set_antialiased(antialiased)
     90         self.set_hatch(hatch)

D:\anaconda3\lib\site-packages\matplotlib\patches.py in set_linewidth(self, w)
    391                 w = mpl.rcParams['axes.linewidth']
    392 
--&gt; 393         self._linewidth = float(w)
    394         # scale the dash pattern by the linewidth
    395         offset, ls = self._us_dashes

TypeError: only size-1 arrays can be converted to Python scalars

解决方法

错误根源是返回的y是嵌套列表包裹的DataFrame切片,而plt.bar需要一维的数值序列(列表或numpy数组),格式不匹配。同时原代码中处理y_axis的循环逻辑完全多余,直接提取分组后的均值数值即可。

修正后的函数及调用代码

import matplotlib.pyplot as plt

def correlation_group(feature):
    # 按species分组,直接提取目标特征的均值
    grouped_mean = df[['species', feature]].groupby('species')[feature].mean()
    # x轴用分组后的索引(即species名称),保证和y轴数值顺序一致
    x_axis = grouped_mean.index.tolist()
    # y轴取均值的数值部分,转为列表格式
    y_axis = grouped_mean.values.tolist()
    return x_axis, y_axis

# 调用函数并绘制柱状图
target_feature = 'sepal_length'
x, y = correlation_group(target_feature)
plt.bar(x, y)
plt.title(f'平均{target_feature}按物种分布')
plt.xlabel('物种')
plt.ylabel(f'平均{target_feature}')
plt.show()

关键修正点

  1. 简化y轴数据处理:直接通过groupby('species')[feature].mean()获取目标特征的分组均值,删除多余的循环和嵌套列表操作
  2. 保证x/y轴顺序一致:用分组后的index作为x轴数据,避免df.species.unique()可能导致的顺序不匹配问题
  3. 输出正确格式:将均值转为列表,符合plt.bar对高度参数的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:40:49