Sorting a boxplot based on median value

梦想与她 提交于 2019-11-29 22:55:37

Check out ?reorder. The example seems to be what you want, but sorted in the opposite order. I changed -count in the first line below to sort in the order you want.

  bymedian <- with(InsectSprays, reorder(spray, -count, median))
  boxplot(count ~ bymedian, data = InsectSprays,
          xlab = "Type of spray", ylab = "Insect count",
          main = "InsectSprays data", varwidth = TRUE,
          col = "lightgray")

Yes, that is the idea:

> set.seed(42)                     # fix seed       
> DF <- data.frame(type=sample(LETTERS[1:5], 100, replace=TRUE), 
+                  cost=rnorm(100)) 
>
> boxplot(cost ~ type, data=DF)    # not ordered by median
>
> # compute index of ordered 'cost factor' and reassign          
> oind <- order(as.numeric(by(DF$cost, DF$type, median)))    
> DF$type <- ordered(DF$type, levels=levels(DF$type)[oind])   
>
> boxplot(cost ~ type, data=DF)    # now it is ordered by median
Wouter Bollaert

Beware of missing values, you have to add na.rm = TRUE for it to work. If not, the code simply doesn't work. It took me hours to found that out.

  bymedian <- with(InsectSprays, reorder(spray, -count, median, **na.rm = TRUE**)
  boxplot(count ~ bymedian, data = InsectSprays,
          xlab = "Type of spray", ylab = "Insect count",
          main = "InsectSprays data", varwidth = TRUE,
          col = "lightgray")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!