gpt4 book ai didi

python - key 错误 : 'type' while drawing a scatter plot with grouped x axis in Python

转载 作者:行者123 更新时间:2023-11-30 22:31:25 25 4
gpt4 key购买 nike

我想绘制一个带有 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()

enter image description here

关于python - key 错误 : 'type' while drawing a scatter plot with grouped x axis in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45820774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com