1

I would like to draw a scatter plot with x and y axis with x axes grouped. x axis will be three types(e.g. h, o, c), which is identifiable by ID column. y axis will have mean values per each ID.

Here's sample data:

       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 axis will be "mean" column value and X axis will be grouped "id" value. When I run my code below, it generates an error:

 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 my code:

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)
2
  • Which line is it failing on? Commented Aug 22, 2017 at 14:46
  • @bendl this line, ax = df.plot.scatter(x='type', y='mean', c=col) Commented Aug 22, 2017 at 14:49

1 Answer 1

5

the x-axis of your scatter plot needs to by a numeric value. You can bypass this by creating a numeric id for your values and map them back to the plot with labels

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.