python - 如何使用 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)?
解决方案
您可以像在 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 中此功能的更详细说明,请参阅此答案。
推荐阅读
- uitableview - 如何在单元格之间的 UITABLEVIEW 中添加间距?
- node.js - mongodb mongoose中的重复键错误索引
- php - 在 WooCommerce 购物车上定位特定产品 ID 显示数量
- r - R Shiny - 我的观察函数({UpdateSelectInput})有什么问题?
- sql - SQL WHERE IN,每个 IN id 的结果有限且已排序
- ruby-on-rails - Rails Sitemap_generator 使用 aws_fog 配置
- javascript - 使用位置和滑动进行水平滚动
- python - 如何将对象添加到 Sphinx 的全局索引,或通过别名进行交叉引用?
- encryption - 如何使 AesEncrypterHandler 以与 Aes 相同的方式加密
- azure - 从本地 SSIS 包中读取 Azure Key Vault 机密