Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading