使用 stat="count" 时将 geom_bar 从高到低重新排序

sag*_*omb 7 r ggplot2

我想在使用 stat="count" 时将 geom_bar 图从高到低重新排序,以便我可以应用填充。

我尝试使用 geom_bar(aes(x = reorder(x, -stat(count)), fill = type) 但它不起作用并抛出错误“错误:stat_count 需要以下缺失的美学:x”

library(ggplot2)
df <- data.frame(x = c("Bob", "James", "Mary", "Sally", "Timmy", "Sally", "Sally", "Bob", "Bob", "Mary"), type = c("A", "B", "A", "B", "B", "C", "B", "B", "A", "B"))
ggplot(df) +
  geom_bar(aes(x = x, fill = type), stat = "count") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
Run Code Online (Sandbox Code Playgroud)

我希望条形从左侧的最高计数到右侧的最低计数进行排序。

aos*_*ith 8

我不确定ggplot2解决方案,但我会使用forcats包来解决这个问题。有一个功能fct_infreq()可以按频率顺序设置因子水平。

然后你可以这样做:

ggplot(df) +
    geom_bar(aes(x = forcats::fct_infreq(x), fill = type)) +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


小智 5

这是reorder来自ggplot2的解决方案:

首先,您需要按名称计算出现次数:

df2 <- df %>% group_by(x) %>%   mutate(count_name_occurr = n())
Run Code Online (Sandbox Code Playgroud)

然后在指定 x 轴时,按名称出现的降序对 x 重新排序。

g2<-ggplot(data=df2, aes(x=reorder(x,-count_name_occurr), fill=type)) +
  geom_bar(stat="count")
g2
Run Code Online (Sandbox Code Playgroud)