Retaining category order when charting/plotting ordered categorical Series
请考虑以下类别
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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] |
我想绘制这些饼图或条形图。根据此SO答案,绘制类别
1 | df.value_counts().plot.bar() |
如何绘制有序的分类变量并保留排序?
您可以在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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() |
或添加
1 2 3 4 5 6 7 8 | print df.value_counts().sort_index() bad 2 ok 1 good 2 awful 2 dtype: int64 print df.value_counts().sort_index().plot.bar() |