我定义了一个函数来从存储在数据框中的分类变量创建堆叠条形图。现在我想在图中显示每个条形的百分比,如下图所示:
我用geom_text下面的方式尝试过,但显然这不起作用。'错误:美学长度必须为 1 或与数据相同:'
BarplotStacked <- function(df, ColName, YearCol){
percentData <- df %>%
select(.dots = c(ColName, YearCol)) %>%
group_by(format(as.Date(.dots2),"%Y")) %>%
count(.dots1) %>%
mutate(ratio=scales::percent(n/sum(n)))
ggplot(df, aes(x=format(as.Date(df[,YearCol]),"%Y"))) +
geom_bar(aes(fill = df[,ColName], y = (..count..)/sum(..count..)),
position="fill") +
scale_y_continuous(labels = percent, limits = c(0,1)) +
geom_text(data=percentData, aes(y = n, label = ratio), # does not work in this way
position=position_fill(vjust = 0.5)) +
coord_flip()
}