1

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.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • Could you please share a sample of your data and the code used for that plot in order to help you?? – Duck Sep 19 '20 at 14:58
  • 1
    I'd suggest looking at the `forcats` package in this post https://stackoverflow.com/questions/3253641/order-discrete-x-scale-by-frequency-value – LRRR Sep 19 '20 at 15:16
  • I think @LRRR's comment is the hint you need: order of `factor`s is almost always the solution to "order of" questions using `ggplot2`. If you still need help, it will be very useful for you to make this question reproducible. This includes sample code you've attempted (including listing non-base R packages, and any errors/warnings received), sample *unambiguous* data (e.g., `dput(head(x))` or `data.frame(x=...,y=...)`), and intended output given that input. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Sep 19 '20 at 15:50

2 Answers2

1

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

tamtam
  • 3,541
  • 1
  • 7
  • 21
0

You can also align the factors then draw the plot.

df$Situation <- factor(df$Situation, levels = c("Before", "After"))
yhy
  • 71
  • 3