Order discrete x scale by frequency/value

前端 未结 5 973
悲哀的现实
悲哀的现实 2020-11-21 10:57

I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the

5条回答
  •  面向向阳花
    2020-11-21 11:38

    Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

    library(ggplot2)
    library(forcats)
    
    ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
    geom_bar() +
    labs(x = "cyl")
    

    If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

    ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
    geom_bar() +
    labs(x = "cyl") 
    

提交回复
热议问题