首页 > 解决方案 > 如何使用 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', '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()
)

上面的代码取自这里

如何value在每个栏的每个类别中间放置标签(在本例中为 s)?

标签: pythonpython-3.xplotnine

解决方案


您可以像在 ggplot2 中一样(plotnine 以高保真度复制它),将“值”映射到美学标签并添加geom_text(使用堆栈定位,在本示例中垂直居中):

(ggplot(df, aes(x='variable', y='value', fill='category', label='value'))
 + geom_col()
 + geom_text(position=position_stack(vjust=0.5))
)

带标签的条形图

有关原始 ggplot2 中此功能的更详细说明,请参阅此答案。


推荐阅读