Order discrete x scale by frequency/value

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

    You can use reorder:

    qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")
    

    Edit:

    To have the tallest bar at the left, you have to use a bit of a kludge:

    qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
       data=mtcars,geom="bar")
    

    I would expect this to also have negative heights, but it doesn't, so it works!

提交回复
热议问题