【问题标题】:Retaining category order when charting/plotting ordered categorical Series绘制/绘制有序分类系列时保留类别顺序
【发布时间】:2016-03-08 00:11:25
【问题描述】:

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

我想画一个饼图或条形图。根据this SO answer,绘制分类Series 需要我绘制value_counts,但这不保留分类顺序:

df.value_counts().plot.bar()

如何绘制有序分类变量并保留顺序?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以在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()
    

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

    【讨论】:

    • 第二个解决方案应该是第一个。
    • @Alexander - 谢谢,已交换解决方案。
    猜你喜欢
    • 2012-12-15
    • 2021-03-28
    • 1970-01-01
    • 2021-12-20
    • 2019-02-26
    • 2018-10-25
    • 2016-12-24
    • 2013-12-22
    相关资源
    最近更新 更多