繁体   English   中英

如何重新排序 geom_bar 图表的条形图?

[英]How to reorder the bars of a geom_bar chart?

所以我有这样的数据:

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

我想 plot 他们,但按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()

Output:

在此处输入图像描述

奖励:如果你想在正确的位置标签试试这个:

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
            hjust=-0.5,vjust=-0.25,     #nudge above top of bar
            size = 3) +
  theme(axis.text.x=element_text(angle = 90, vjust = 0.5))+ 
  theme(legend.position = "none") +
  coord_flip()

Output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM