Reorder geom_bar or anything else in ggplot by the value of your choosing

You still find recent answers on StackOverflow counseling to redefine the factors of a data.frame to reorder elements of a ggplot graphic. In the 2020’s, this can be avoided. Factors are a heritage of a numerical focus of R, when text values were seen as an anomaly or, at best, as ordinal values. I highly recommend leaving the data.frame framework to work with data.table.

Today, if you want to reorder geom_bar or anything else in ggplot by the value of your choosing, there is a one-word solution, called “reorder”. You can use this function when defining the x value in the aes() parameters. Example:

ggplot(data) +  geom_bar(aes(x=reorder(feature,frequency),y=frequency),stat="identity")

Find the a good example on StackOverflow regarding this here.




  •  
  •  
  •  
  •  
  •  

Leave a comment

Your email address will not be published. Required fields are marked *