如何解决我如何使用ggplot2控制条的顺序
我正在尝试使用下面dput
中的数据来生成水平并排的ggplot barplot
所需的输出
我需要一个按此顺序排列在翻转版本中的并排barplot:
- 顶部为紫红色的“年轻人”
- “ 55+,中间为灰色77”
- 底部为铁蓝色的70 +
当前进度
ggplot(AF.dummy,aes(fill=Agegroup,y=sumofweights,x=reorder(Place,sumofweights))) +
geom_bar(position="dodge",stat="identity",width = 0.75)+scale_fill_manual(values = c("steelblue","violetred3","gray77"))+
geom_text(aes(label=Response_pct),vjust=0.5,hjust=0.5,color='black',size=2,position=position_dodge(width=0.9))+
xlab('')+ ylab('Survey response (%)')+ theme_classic()+ scale_y_continuous(expand = c(0,NA),limits = c(0,110))+theme(axis.text = element_text(size=25),plot.title = element_text(color="black",size=14,face="bold.italic"),axis.text.x = element_blank(),axis.title=element_text(size=25),axis.text.y = element_text(colour = "black"),legend.text = element_text(size = 25),legend.position = "bottom")+coord_flip()
但是,这会在顶部产生年轻的个体,但会产生灰色,在中间产生70+紫色,在底部产生55-69的蓝色。即使尝试不同的颜色顺序,也不会按照我需要的顺序放置条形。
structure(list(Place = c("a","a","k","d","e","y","n","s","m","m"),Full_Question = c("How old is your?","How old is your?","How old is your?"
),Agegroup = c("55-69","70+","Younger individuals","55-69","Younger individuals"
),sumofweights = c(40.5267641630215,40.0599884082414,49.8850932240653,88.2272464391841,89.6683573987055,87.0721200154442,24.2153456875521,21.8526096685293,28.8586215334053,31.3193116688862,37.9323356937974,30.4203477914831,93.7928409385601,95.6887643725211,92.4444551282296,88.2382569688424,88.8346819477341,82.7930606656007,95.9438110968709,93.585465536874,95.6929909239288,91.3775427133175,91.4190494705697,88.6228191085142,43.2470752073293,46.8078562440572,49.0305923706361,15.6955797447921,9.93685539029956,19.5632067880936,97.8278268705863,99.0720566387276,97.373146423847,94.528643616569,96.6159714111715,94.6539500397186,98.8983300765884,98.1456203247728,97.9251511366201,6.95189707677415,10.4796004809264,7.94764360599454,82.9482534171168,81.6443772785483,81.247100231254),Response_pct = c("41%","40%","50%","88%","90%","87%","24%","22%","29%","31%","38%","30%","94%","96%","92%","89%","83%","91%","43%","47%","49%","16%","10%","20%","98%","99%","97%","95%","7%","8%","82%","81%")),row.names = c(NA,-45L),groups = structure(list(Place = c("a","y"),"How old is your?"),.rows = structure(list(
c(1L,2L,3L,4L,5L,6L,34L,35L,36L),10:12,c(13L,14L,15L,31L,32L,33L),7:9,43:45,c(22L,23L,24L,37L,38L,39L,40L,41L,42L),25:27,c(16L,17L,18L,19L,20L,21L,28L,29L,30L)),ptype = integer(0),class = c("vctrs_list_of","vctrs_vctr","list"))),8L),class = c("tbl_df","tbl","data.frame"),.drop = TRUE),class = c("grouped_df","tbl_df","data.frame"))
解决方法
(SO上的)每一个包含ggplot2和“ ...的顺序” 的问题都可以通过使用factor
来解决。 Ggplot2将遵守因数levels
建议的顺序。
unique(AF.dummy$Agegroup)
# [1] "55-69" "70+" "Younger individuals"
AF.dummy$Agegroup <- factor(AF.dummy$Agegroup,levels=c("Younger individuals","55-69","70+"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。