2017-08-22 65 views
1

我想繪製x軸和y軸分散繪圖,x軸分組。 x軸將是三種類型(例如,h,o,c),其可由ID列識別。 y軸將具有每個ID的平均值。KeyError:'type'在Python中繪製帶有分組x軸的散點圖

這裏的示例數據:

 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' 

Here'e我的代碼:

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) 
+0

哪行沒有它的情節? – bendl

+0

@bendl this line,'ax = df.plot.scatter(x ='type',y ='mean',c = col)' – ejshin1

回答

3

你的散點圖的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