本文介绍了ggplot用geom_bar中的百分比替换count的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个dataframe d : > (d,20) groupchange Symscore3 1 4 1 2 4 2 3 4 1 4 4 2 5 5 0 6 5 0 7 5 0 8 4 0 9 2 2 10 5 0 11 5 0 12 5 1 13 5 0 14 4 1 15 5 1 16 1 0 17 4 0 18 1 1 19 5 0 20 4 0 我正在绘制: ggplot(d,aes(groupchange,y = .. count ../ sum(.. count ..),fill = Symscore3))+ geom_bar(position = 闪避) 通过这种方式,每个小节代表整个数据的百分比。 相反,我希望每个栏代表一个相对百分比;即用 groupchange = k 获得的柱的总和应该是 1 。 library() dplyr) d2 % group_by(groupchange,Symscore3)%>%汇总(count = n())%>% mutate (perc = count / sum(count)) 然后您可以绘制它: ggplot(d2,aes(x = factor(groupchange),y = perc * 100,fill = factor(Symscore3))+ geom_bar(stat =identity,width = 0.7)+ labs(x =Groupchange,y =percent,fill =Symscore)+ theme_minimal(base_size = 14) 这给出: 或者,您可以使用 percent 功能n来自比例包: brks ggplot(d2,aes(x = factor(groupchange),y = perc,fill = factor(Symscore3)))+ geom_bar(stat =identity,width = 0.7)+ scale_y_continuous(breaks = brks,labels = scales :: percent(brks))+ labs(x =Groupchange,y = NULL,fill = Symscore)+ theme_minimal(base_size = 14) 给出: I have a dataframe d:> head(d,20) groupchange Symscore31 4 12 4 23 4 14 4 25 5 06 5 07 5 08 4 09 2 210 5 011 5 012 5 113 5 014 4 115 5 116 1 017 4 018 1 119 5 020 4 0That I am plotting with:ggplot(d, aes(groupchange, y=..count../sum(..count..), fill=Symscore3)) + geom_bar(position = "dodge")In this way each bar represents its percentage on the whole data.Instead I would like that each bar represents a relative percentage; i.e. the sum of the bar in obtained with groupchange = k should be 1. 解决方案 First summarise and transform your data:library(dplyr)d2 <- d %>% group_by(groupchange,Symscore3) %>% summarise(count=n()) %>% mutate(perc=count/sum(count))Then you can plot it:ggplot(d2, aes(x = factor(groupchange), y = perc*100, fill = factor(Symscore3))) + geom_bar(stat="identity", width = 0.7) + labs(x = "Groupchange", y = "percent", fill = "Symscore") + theme_minimal(base_size = 14)this gives:Alternatively, you can use the percent function from the scales package:brks <- c(0, 0.25, 0.5, 0.75, 1)ggplot(d2, aes(x = factor(groupchange), y = perc, fill = factor(Symscore3))) + geom_bar(stat="identity", width = 0.7) + scale_y_continuous(breaks = brks, labels = scales::percent(brks)) + labs(x = "Groupchange", y = NULL, fill = "Symscore") + theme_minimal(base_size = 14)which gives: 这篇关于ggplot用geom_bar中的百分比替换count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-19 03:40