KeyError:在 Python 中绘制带有分组 x 轴的散点图时出现“类型”

ejs*_*in1 1 python matplotlib pandas

我想绘制一个带有 x 和 y 轴的散点图,其中 x 轴分组。x轴有三种类型(例如h、o、c),可以通过ID列来识别。y 轴将具有每个 ID 的平均值。

这是示例数据:

       id   sum       mean    color  type
0     109  2852    5.301115     r      h
1     110  3162    5.877323     r      h
2     111  1997    3.711896     b      o
Run Code Online (Sandbox Code Playgroud)

Y 轴将是“平均”列值,X 轴将是分组“id”值。当我运行下面的代码时,它会生成错误:

 File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)
 File "pandas\src\hashtable_class_helper.pxi", line 732, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)
 File "pandas\src\hashtable_class_helper.pxi", line 740, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)
 KeyError: 'type'
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

df.set_index('type', inplace=True)
...
col = df['type'].map({'h':'r', 'o':'b', 'c':'y'})
ax = df.plot.scatter(x='type', y='mean', c=col)
Run Code Online (Sandbox Code Playgroud)

Deb*_*Deb 5

散点图的 x 轴需要一个数值。您可以通过为您的值创建一个数字 ID 并将它们映射回带有标签的绘图来绕过此问题

df['type'] = df['type'].astype('category')
df['type_id'] = df.type.cat.codes
plt.scatter(x=df['type_id'], y=df['mean'], color=df['color'])
plt.xticks(df['type_id'].tolist(), df['type'], rotation=90)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述