KeyError:';类型';在Python中绘制带有分组x轴的散点图时

KeyError:';类型';在Python中绘制带有分组x轴的散点图时,python,pandas,matplotlib,Python,Pandas,Matplotlib,我想画一个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 Y轴将是“平均”列值,X轴将

我想画一个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
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'
这是我的密码:

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)

散点图的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()

散点图的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()

哪一行失败?@bendl这一行,
ax=df.plot.scatter(x='type',y='mean',c=col)
哪一行失败?@bendl这一行,
ax=df.plot.scatter(x='type',y='mean',c=col