Search code examples
rggplot2reverseboxplot

GGplot reverse the boxplot sequence


How can I reverse the order of Boxplot. In the picture you can see that 'After' is shown ahead of 'Before'. I want to reverse the order.


Solution

  • You can use fct_rev for reversing the order of a factor or fct_relevel for changing the order manually.

    Here is an example df.

    df <- data.frame(values = rnorm(n = 300, mean = 50, sd = 15),
                     time = factor(rep(c(30, 40, 50), 100)),
                     situation = rep(c("Before", "After"), each = 150))
    
    

    And here a example codes for the problem.

    library(ggplot2)
    library(forcats)
    
    ggplot(df) +
      geom_boxplot(aes(x = time, 
                       y = values, 
                       color = fct_rev(situation))) +
      guides(color = guide_legend(title = "situation"))
    
    
    ggplot(df) +
      geom_boxplot(aes(x = time, 
                       y = values, 
                       color = fct_relevel(situation, "After", after = 1))) +
      guides(color = guide_legend(title = "situation"))
    

    Both codes result in this plot.

    enter image description here