Home > Mobile >  Rearrange multiple ggplot order in R
Rearrange multiple ggplot order in R

Time:11-01

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?

CodePudding user response:

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

CodePudding user response:

Try this:

data_def$name = factor(data_def$name, 
                          levels = c("X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9", "X10", "X11", "X12"))

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")

enter image description here

  • Related