如何使用ggplot geom_bar在堆积列中显示百分比? [英] How to show percentages in stacked column with ggplot geom_bar?

查看:224
本文介绍了如何使用ggplot geom_bar在堆积列中显示百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的数据

  myresults = data.frame(操作= 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"))),值= c(73,83,76,75,78,261,301,344,451,599,866,816,780,674,523)) 

I'm trying to add percentage labels in a stacked bar chart. What can I add to my geom_bar to show the percentage labels inside stacked bars?

This is my data:

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))

This is my bar chart, without percentage labels.

I have little knowledge in this. I googled "gglot stacked bar percentage label" and found that adding percentage labels could be done with "+ geom_text(stat="count")".

But when I added + geom_text(stat="count") to my ggplot geom_bar, R said "Error: stat_count() must not be used with a y aesthetic." I tried to figure out what a y aesthetic is, but it hasn't been very successful.

This is what I did:

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")

解决方案

You can do something similar to the accepted answer in: Adding percentage labels to a bar chart in ggplot2. The main difference is that your values are piled up( "stacked") whereas in that example it is side by side ("dodged")

Make a column of percentages:

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

Now we plot this:

    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)

The important parameters in geom_text is position="stacked", and play around with vjust, to move up or down your label. (I apologize in advance for the awful text color..).

这篇关于如何使用ggplot geom_bar在堆积列中显示百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆