Python 如何使用plotnine对叠层钢筋进行排序

Python 如何使用plotnine对叠层钢筋进行排序,python,python-3.x,pandas,plotnine,Python,Python 3.x,Pandas,Plotnine,我有以下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'

我有以下
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()
)
以上代码取自


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

您可以使用
pd.category
函数和
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)