pandas 情节栏订购类别 [英] Pandas plot bar order categories

查看:44
本文介绍了 pandas 情节栏订购类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含分类变量的数据集,该变量包含三个唯一值"low","medium"和"high":

I have a dataset with a categorical variable that contains three unique values, "low", "medium" and "high":

df.CatVar.value_counts()
Out[93]: 
Medium    35832
Low       25311
High      12527
Name: CatVar, dtype: int64

我正在尝试将唯一值的数量绘制为条形图.但是,下面的代码按[[Medium],"Low","High"]的顺序显示了条形图

I am trying to plot the number of unique values as a bar-plot. However, the following code gives me the bars in the order ["Medium", "Low", "High"]

df.CatVar.value_counts().plot(kind="bar")

如何更改绘图中条形的顺序?

How do I change the order of the bars in the plot?

推荐答案

有两种可能的解决方案-在绘制前更改index的顺序-通过

There are 2 possible solutions - change order of index before plot - by reindex or loc:

df.CatVar.value_counts().reindex(["Low", "Medium", "High"]).plot(kind="bar")

df.CatVar.value_counts().loc[["Low", "Medium", "High"]].plot(kind="bar")

或使用 ordered categorical ,因此在value_counts之后得到按categories参数排序:

Or use ordered categorical, so after value_counts get order by categories parameter:

df.CatVar = pd.Categorical(df.CatVar, categories=["Low", "Medium", "High"], ordered=True)
df.CatVar.value_counts(sort=False).plot(kind="bar")


示例:

df = pd.DataFrame({'CatVar':['Low','Medium','Low','Low','Medium','High']})
print (df)
   CatVar
0     Low
1  Medium
2     Low
3     Low
4  Medium
5    High

df.CatVar.value_counts().reindex(["Low", "Medium", "High"]).plot(kind="bar")

这篇关于 pandas 情节栏订购类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆