如何解决如何重新排列geom_bar图表的条形图?
所以我有这样的数据:
df <- structure(list(bin = structure(c(14L,13L,12L,11L,10L,9L,8L,7L,6L,5L,4L,3L,1L,2L),.Label = c("A","B","C","K","EE","F","G","H","I","SS","AR","W","D","T"),class = "factor"),count = c(514L,504L,145L,131L,96L,80L,63L,38L,34L,26L,24L,20L,18L,18L),pct = c("30.0%","29.5%","8.5%","7.7%","5.6%","4.7%","3.7%","2.2%","2.0%","1.5%","1.4%","1.2%","1.1%","1.1%"
)),row.names = c(NA,-14L),class = c("tbl_df","tbl","data.frame"
))
我想绘制它们,但在count
上订购但我无法使它工作。无法使用reorder
...
ggplot(df,aes(y=count,x=reorder(as.factor(bin),count),label = pct)) +
geom_bar(position="dodge",stat="identity")+
aes(stringr::str_wrap(as.factor(bin),15),count) +
geom_col(fill = "mediumpurple2")+
labs(x = "",y = "Count",fill = "")+
lims(y = c(0,550)) +
geom_text(position = position_dodge(width = .9),#move to center of bars
vjust = -0.5,#nudge above top of bar
size = 3) +
theme_hc() +
theme(axis.text.x=element_text(angle = 90,vjust = 0.5))+
theme(legend.position = "none") +
coord_flip()
我已经多次遇到这个问题,所以对我做错的事情的解释将非常有帮助!
解决方法
我建议您在方法上稍作改动:
library(ggplot2)
#Data
ggplot(df,aes(y=count,x=reorder(stringr::str_wrap(as.factor(bin),15),count),label = pct)) +
geom_bar(position="dodge",stat="identity")+
geom_col(fill = "mediumpurple2")+
labs(x = "",y = "Count",fill = "")+
lims(y = c(0,550)) +
geom_text(position = position_dodge(width = .9),#move to center of bars
vjust = -0.5,#nudge above top of bar
size = 3) +
theme(axis.text.x=element_text(angle = 90,vjust = 0.5))+
theme(legend.position = "none") +
coord_flip()
输出:
奖金:如果您希望标签放置在正确的位置,请尝试以下操作:
ggplot(df,#move to center of bars
hjust=-0.5,vjust=-0.25,vjust = 0.5))+
theme(legend.position = "none") +
coord_flip()
输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。