Reputation: 78723
Consider the following categorical pd.Series
:
In [37]: df = pd.Series(pd.Categorical(['good', 'good', 'ok', 'bad', 'bad', 'awful', 'awful'], categories=['bad', 'ok', 'good', 'awful'], ordered=True))
In [38]: df
Out[38]:
0 good
1 good
2 ok
3 bad
4 bad
5 awful
6 awful
dtype: category
Categories (4, object): [bad < ok < good < awful]
I want to draw a pie or bar chart of these. According to this SO answer, plotting categorical Series
requires me to plot the value_counts
, but this does not retain the categorical ordering:
df.value_counts().plot.bar()
How can I plot an ordered categorical variable and retain the ordering?
Upvotes: 2
Views: 330
Reputation: 862611
You can add parameter sort=False
in value_counts
:
print df.value_counts()
awful 2
good 2
bad 2
ok 1
dtype: int64
print df.value_counts(sort=False)
bad 2
ok 1
good 2
awful 2
dtype: int64
print df.value_counts(sort=False).plot.bar()
Or add sort_index
:
print df.value_counts().sort_index()
bad 2
ok 1
good 2
awful 2
dtype: int64
print df.value_counts().sort_index().plot.bar()
Upvotes: 3