How to show percentages in stacked column with ggplot geom_bar? [duplicate]

落爺英雄遲暮 提交于 2021-01-27 18:44:20

问题


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

回答1:


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




回答2:


You can try tu create the position of geom text and put it on the bars:

mydata[, label_ypos := cumsum(value), by = manipulation]

ggplot(myresults, aes(x=manipulation, y=value, fill=variable)) + 
geom_bar(stat="identity", position="fill", colour="black") +
geom_text(aes(y=label_ypos, label= paste(round(rent, 2), '%')), vjust=2, 
        color="white", size=3.5) +
scale_y_continuous(labels = scales::percent) +
labs(x = "Manipulation", y=NULL, fill="Result") +
theme_bw(base_family = "Cambria") +
theme(legend.direction = "vertical", legend.position = "right") +
scale_fill_grey() 


来源:https://stackoverflow.com/questions/58744507/how-to-show-percentages-in-stacked-column-with-ggplot-geom-bar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!