Order discrete x scale by frequency/value

前端 未结 5 952
悲哀的现实
悲哀的现实 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:42

    Try manually setting the levels of the factor on the x-axis. For example:

    library(ggplot2)
    # Automatic levels
    ggplot(mtcars, aes(factor(cyl))) + geom_bar()    
    

    ggplot of the cars dataset with factor levels automatically determined

    # Manual levels
    cyl_table <- table(mtcars$cyl)
    cyl_levels <- names(cyl_table)[order(cyl_table)]
    mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels)
    # Just to be clear, the above line is no different than:
    # mtcars$cyl2 <- factor(mtcars$cyl, levels = c("6","4","8"))
    # You can manually set the levels in whatever order you please. 
    ggplot(mtcars, aes(cyl2)) + geom_bar()
    

    ggplot of the cars dataset with factor levels reordered manually

    As James pointed out in his answer, reorder is the idiomatic way of reordering factor levels.

    mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
    ggplot(mtcars, aes(cyl3)) + geom_bar()
    

    ggplot of the cars dataset with factor levels reordered using the reorder function

提交回复
热议问题