Kobi
Kobi

Reputation: 3

how to plot in pandas categorical data

I have this kind of dataframe:

  animal  age    where
0    dog    1   indoor
1    cat    4   indoor
2  horse    3  outdoor

I would like to present a bar plot in which:

y axis is age, x axis is animal, and the animals are grouped in adjacent bars with different colors.

Thanks

Upvotes: 0

Views: 348

Answers (2)

wwnde
wwnde

Reputation: 26676

Another easy way. Set the intended x axis label as index and plot. By defaul, float/integer end up on the y axis

import matplotlib.pyplot as plt
df.set_index(df['animal']).plot( kind='bar')
plt.ylabel('age')

enter image description here

Upvotes: 1

CutePoison
CutePoison

Reputation: 5355

This should do the trick


df = pd.DataFrame({"animal":["dog","cat","horse"],"age":[1,4,3],"where":["indoor","indoor","outdoor"]})


df
animal  age where
0   dog 1   indoor
1   cat 4   indoor
2   horse   3   outdoor

ax = df.plot.bar(x="animal",y="age",color=["b","r","g"])
ax.legend("")
ax.set_ylabel("Age")

enter image description here

Upvotes: 1

Related Questions