How to properly sort facet boxplots by median?

后端 未结 2 435
天命终不由人
天命终不由人 2021-01-19 14:26

I\'m using the \'diamonds\' dataset that comes with R. When trying to sort the \'color\' factor with respect to their price median it won\'t work.

This is what I got

2条回答
  •  执笔经年
    2021-01-19 15:05

    ggplot(diamonds, aes(x = reorder(color, -price, FUN=median), y = price)) + 
          geom_boxplot() + 
          facet_wrap(~cut) + 
          ylim(0, 5500)
      levels(diamonds$color) # "D" "E" "F" "G" "H" "I" "J"
      diamonds$color <- reorder(diamonds$color, -diamonds$price, FUN=median)
      levels(diamonds$color)  # "J" "I" "H" "F" "G" "D" "E"
      ggplot(diamonds, aes(x =color, y = price))+
          geom_boxplot() + 
          facet_wrap(~cut) + 
          ylim(0, 5500)
    

    In fact what you have the following order

      ggplot(diamonds, aes(x =color, y = price))+
          geom_boxplot() + 
          ylim(0, 5500)
    

    But the answer from missuse is very nice.

提交回复
热议问题