Matplotlib问题将值的#匹配到标签的数量— ValueError:'标签'的长度必须为'x'

问题描述 投票:0回答:1

我有一个名为high的df,看起来像这样:

   white  black  asian  native  NH_PI  latin
0  10239  26907   1079     670     80   1101`

我正在尝试使用matplotlib创建一个简单的饼图。我看过多个示例和其他SO页面,例如this one,但我一直收到此错误:

Traceback (most recent call last):
  File "I:\Sustainability & Resilience\Food Policy\Interns\Lara Haase\data_exploration.py", line 62, in <module>
    plt.pie(sizes, explode=None, labels = high.columns, autopct='%1.1f%%', shadow=True, startangle=140)
  File "C:\Python27\ArcGIS10.6\lib\site-packages\matplotlib\pyplot.py", line 3136, in pie
    frame=frame, data=data)
  File "C:\Python27\ArcGIS10.6\lib\site-packages\matplotlib\__init__.py", line 1819, in inner
    return func(ax, *args, **kwargs)
  File "C:\Python27\ArcGIS10.6\lib\site-packages\matplotlib\axes\_axes.py", line 2517, in pie
    raise ValueError("'label' must be of length 'x'")
ValueError: 'label' must be of length 'x'`

我尝试了多种不同的方法来确保标签和值匹配。每个都有6个,但是我不明白为什么Python与我不同意。

这是我尝试过的一种方法:

plt.pie(high.values, explode=None, labels = high.columns, autopct='%1.1f%%', shadow=True, startangle=140)

另一种方式:

labels = list(high.columns)
sizes = list(high.values)
plt.pie(sizes, explode=None, labels = labels, autopct='%1.1f%%', shadow=True, startangle=140)`

也尝试使用.iloc

labels = list(high.columns)
sizes = high.loc[[0]]
print(labels)
print(sizes)
plt.pie(sizes, explode=None, labels = labels, autopct='%1.1f%%', shadow=True, startangle=140)

但是无论我尝试了什么,我都会不断遇到同样的关键错误。有什么想法吗?

pandas list dataframe matplotlib pie-chart
1个回答
1
投票

您可以尝试使用熊猫数据框图进行此操作:

df.T.plot.pie(y=0, autopct='%1.1f%%', shadow=True, startangle=140, figsize=(10,8), legend=False)

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.