我定义了一个函数,用于根据存储在数据框中的类别变量创建堆叠的条形图。现在,我想在图中显示每个条形的百分比,如下图:
我以下面的方式用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()
}