首页 > 解决方案 > 如何使用ggplot geom_bar在堆积列中显示百分比?

问题描述

我正在尝试在堆积条形图中添加百分比标签。我可以添加什么到我的 geom_bar 以显示堆叠条内的百分比标签?

这是我的数据:

myresults=data.frame(
    manipulation=rep(c(-20,-10,0,10,20,-20,-10,0,10,20,-20,-10,0,10,20)),
    variable=rep(c("a","a","a","a","a","f","f","f","f","f","l","l","l","l","l")),
    value=c(73,83,76,75,78,261,301,344,451,599,866,816,780,674,523))

这是我的条形图,没有百分比标签。

我对此知之甚少。我搜索了“gglot 堆积条百分比标签”,发现可以使用“+ geom_text(stat="count")”添加百分比标签。

但是当我将 + geom_text(stat="count") 添加到我的 ggplot geom_bar 时,R 说“错误:stat_count() 不能与任何美学一起使用。” 我试图弄清楚什么是审美,但它并不是很成功。

这就是我所做的:

mydata <- ggplot(myresults, aes(x=manipulation, y=value, fill=variable))

mydata + geom_bar(stat="identity", position="fill", colour="black") + scale_fill_grey() + scale_y_continuous(labels=scales::percent) + theme_bw(base_family="Cambria") + labs(x="Manipulation", y=NULL, fill="Result") + theme(legend.direction="vertical", legend.position="right")

标签: rggplot2geom-bar

解决方案


您可以执行类似于以下已接受答案的操作: 在 ggplot2 中向条形图添加百分比标签。主要区别在于您的值是堆积的(“堆叠”),而在该示例中它是并排的(“躲避”)

制作一列百分比:

myresults_pct <- myresults %>% 
group_by(manipulation) %>% 
mutate(pct=prop.table(value))

现在我们绘制这个:

    ggplot(myresults_pct, 
aes(x=manipulation, y=pct,fill=variable)) + 
geom_col()+
scale_fill_grey()+
geom_text(aes(label = scales::percent(pct)),
position="stack",vjust=+2.1,col="firebrick",size=3)+
scale_y_continuous(label = scales::percent)

geom_text 中的重要参数是 position="stacked",并使用 vjust 来上下移动标签。(我提前为糟糕的文字颜色道歉..)。

在此处输入图像描述


推荐阅读