【问题标题】:How to put labels in a stacked bar using plotnine如何使用 plotnine 将标签放在堆叠栏中
【发布时间】:2018-10-05 10:13:26
【问题描述】:

我有以下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

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

【问题讨论】:

  • 有什么理由不想要 matplotlib?如果您很灵活,this 解决方案可能会对您有所帮助。此外,您共享的链接包含示例,如果您向下滚动,它们会在顶部用值注释条
  • 标签在条的顶部,而不是在堆叠条的中间:(

标签: python python-3.x plotnine


【解决方案1】:

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

请参阅this answer 以获取原始 ggplot2 中有关此功能的更详细说明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多