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

multiple ggplot in R

I have dataset in R as follows:

set.seed(123)
data <- as.data.frame(matrix(rnorm(20 * 5, mean = 0, sd = 1), 20, 5))
colnames(data) <- c("Y", paste0("X", 1:4))

and I want to create all possible plots between Y and X‘s. For a simple plot I can do this:

par(mfrow = c(2, 2))
for (i in seq(ncol(data))[-1]) {
  plot(data[, 1], data[, i], xlab = colnames(data)[i], ylab = "Y")
}

How can create the equivalent plots based on ggplot function. I created the following but I can not make it work.

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

par(mflow = c(2,2))
for (i in seq(ncol(data))[-1]){
ggplot(data, aes(x = data[,i], y = data[,1])) +
  labs(x = colnames(data)[i], y = "Y") +
  stat_smooth() +
  geom_point(color = "gray40", alpha = .5)
  
} 

>Solution :

When using ggplot2 you are most of the time better off by reshaping your data to long or tidy format using e.g. tidyr::pivot_longer. After doing so you could e.g. use facet_wrap to get you plots for each X:

library(tidyr)
library(ggplot2)

data_long <- pivot_longer(data, -Y, names_to = "name", values_to = "value")

ggplot(data_long, aes(x = value, y = Y)) +
  stat_smooth() +
  geom_point(color = "gray40", alpha = .5) +
  facet_wrap(~name)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

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