在R中使用ggplot2显示堆叠条形图中的百分比

时间:2019-10-16 12:07:23

标签: r ggplot2

我定义了一个函数,用于根据存储在数据框中的类别变量创建堆叠的条形图。现在,我想在图中显示每个条形的百分比,如下图:enter image description here

我以下面的方式用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()
}

0 个答案:

没有答案