How to reorder x-axis in geom_boxplot by mean of the group in R?

12,273

The easiest way is to use reorder:

d$fac = reorder(d$fac, d$y, mean)

Here we calculate the mean of y conditional on the value of fac. ggplot2 will now order the plot according the order of levels(d$fac)

You can also put the reorder in the ggplot call

# Thanks to renato vitolo
ggplot(d, aes(x=reorder(fac, y, mean), y=y))
Share:
12,273
Admin
Author by

Admin

Updated on July 18, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to be able to reorder the x-axis of a boxplot in ggplot by the mean of each of the groups.

    For example, if I have this data frame:

    L3 <- LETTERS[1:3]
    fac <- sample(L3, 50, replace = TRUE)
    (d <- data.frame(x = 1, y = sample(1:10, 50, replace = TRUE), fac = fac))
    d
    
    p <- ggplot(d, aes(x=fac, y=y)) + geom_boxplot(fill = "#E69F00")
    print(p)

    However, I want to be able to reorder the box plot by the mean of each factor (i.e. A, B, C), instead of the order in the dataframe. I have been looking for an answer for this and have run into several commands but none of them have worked. I am thinking there might be a way using order or reorder and dplyr/summarise, but everything I tried is not working.

    I am not able to upload a picture yet, but let's say that the graph has a mean of 6 for A, 5 for B, and 5.5 for C. I would want the order to be B, C, A. My actual graph has 30 factors, so I want an easy way to do it without ordering it manually.

    I really appreciate all the help!!