在绘制/绘制有序分类系列时保留类别顺序

时间:2016-03-07 15:42:07

标签: python pandas matplotlib

考虑以下分类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]

我想绘制这些饼图或条形图。根据{{​​3}},绘制分类Series需要我绘制value_counts,但这不会保留分类顺序:

df.value_counts().plot.bar()

如何绘制有序的分类变量并保留排序? this SO answer

1 个答案:

答案 0 :(得分:3)

您可以在value_counts中添加参数sort=False

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()

graph

或添加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()