如何重新排列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()

输出:

enter image description here

奖金:如果您希望标签放置在正确的位置,请尝试以下操作:

ggplot(df,#move to center of bars
            hjust=-0.5,vjust=-0.25,vjust = 0.5))+ 
  theme(legend.position = "none") +
  coord_flip()

输出:

enter image description here