【问题标题】:how to order the stacked bar using plotnine如何使用 plotnine 对堆积条进行排序
【发布时间】:2018-10-04 13:07:10
【问题描述】:

我有以下dataframe

import pandas as pd
from plotnine import *

df = pd.DataFrame({
    'variable': ['gender', 'gender', 'age', 'age', 'age', 'income', 'income', 'income', 'income'],
    'category': ['Female', 'Male', '1-24', '25-54', '55+', 'Lo', 'Lo-Med', 'Med', 'High'],
    'value': [60, 40, 50, 30, 20, 10, 25, 25, 40],
})
df['variable'] = pd.Categorical(df['variable'], categories=['gender', 'age', 'income'])

我正在使用以下代码来获取堆积条形图

(ggplot(df, aes(x='variable', y='value', fill='category'))
 + geom_col()
)

以上代码取自here

如何更改每个类别的顺序。例如。我希望 age 1-24 位于 age 堆叠条的底部

【问题讨论】:

    标签: python python-3.x pandas plotnine


    【解决方案1】:

    您可以使用pd.Categorical 函数和ordered=True 来指定堆叠的列顺序。此属性可确保在绘图过程中以您想要的方式保留类别顺序:

    # Categories are shown in a top-down order, 
    # so you must reverse 'ages' order to be shown in bottom-up fashion
    cat_order = ['Female', 'Male', '55+', '25-54', '1-24', 'Lo', 'Lo-Med', 'Med', 'High']
    
    df['category'] = pd.Categorical(df['category'], categories=cat_order, ordered=True)
    

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2021-10-10
      • 1970-01-01
      • 2018-09-30
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      相关资源
      最近更新 更多