Home > OS >  Reordering x-axis by count descending in R
Reordering x-axis by count descending in R

Time:06-22

I have the following count plot in R

mpg %>%
  ggplot2::ggplot(ggplot2::aes(x = as.character(class)))  
  ggplot2::geom_bar(fill = '#00798c')   
  ggplot2::geom_text(stat = "count", ggplot2::aes(label = after_stat(count)), position = ggplot2::position_dodge(width = 0.8), vjust = -0.3) 

How can I reorder the bars to be by descending counts?

I'm not sure if I can use the reorder() function here because there isn't a specific variable for the count. Or am I missing something?

CodePudding user response:

Yes, you can use reorder. You are reordering by the length of each level, so do:

library(ggplot2)

mpg %>%
  ggplot(aes(x = reorder(factor(class), class, length)))  
  geom_bar(fill = '#00798c')   
  geom_text(stat = "count", aes(label = after_stat(count)), 
                     position = position_dodge(width = 0.8), vjust = -0.3) 

enter image description here

CodePudding user response:

We could use a combination: fct_rev(fct_infreq(.... from forcats package it is in tidyverse:

library(tidyverse)
mpg %>%
  ggplot(aes(x = fct_rev(fct_infreq(as.character(class)))))  
  geom_bar(fill = '#00798c')   
  geom_text(stat = "count", ggplot2::aes(label = after_stat(count)), 
            position = ggplot2::position_dodge(width = 0.8), vjust = -0.3) 

enter image description here

  • Related