1

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.

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

1 Answer 1

3

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'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.