Search code examples
rggplot2plotscatter-plot

Rearrange multiple ggplot order in R


I have a matrix in R and I am trying to create plots between first column (Y) with all other columns (Xj j=1,...,12). I am using the following code to do that:

set.seed(123)
dat <- as.data.frame(matrix(rnorm(20 * 13, mean = 0, sd = 1), 20, 13))

colnames(dat) <- c("Y", paste0("X",1:12))

data_def <- pivot_longer(dat, -Y)

ggplot(data_def, aes(x = Y, y = value)) +
  stat_smooth(se = FALSE, color = "red", size = 0.5, method = "loess") +
  facet_wrap( ~ name, scales = "free_y", strip.position = "bottom") +
  theme_classic() +

  labs(x = NULL, y = "Y")

which results in: enter image description here

However after X1 comes X10, X11 and X12 instead of X2, X3, etc.. How can I re arrange the order?


Solution

  • We could use fct_inorder from forcats package: This will keep the order as in your column!:

    library(ggplot2)
    library(forcats)
    
    ggplot(data_def, aes(x = Y, y = value)) +
      stat_smooth(se = FALSE, color = "red", size = 0.5, method = "loess") +
      facet_wrap( ~ fct_inorder(name), scales = "free_y", strip.position = "bottom") +
      theme_classic() +
      
      labs(x = NULL, y = "Y")
    

    enter image description here