0

I am looking to generate ggplot2 scatter plots for each variable combination.

We can use the mtcars dataset as an example -- how can I generate the following graph for every possible column combination?

mpg vs. cyl, mpg vs. disp, etc...

cyl vs. disp, cyl vs. hp, etc...

and so on....

ggplot(mtcars, aes(x = mpg, y = cyl)) +
  geom_point(size = 3.5) +
  guides(fill=guide_legend(override.aes=list(shape=21))) +
  stat_cor(method = "pearson") +
  geom_smooth(method = lm, alpha = 0.1, color = "black")

can a loop be generated and column names be recorded and graphs are sequentially generated and saved as a .tif?

1
  • Sounds like you want ggpairs. You done any searching? Commented Apr 28, 2023 at 20:25

1 Answer 1

0

If your aim is to have var to var correlation plots there are some packages for that like GGally

library(GGally)
ggscatmat(mtcars,columns =c(1,3:5) ,  color = "vs", alpha = 0.8)

Created on 2023-04-28 with reprex v2.0.2

but if your aim is to use your customized plot

library(ggplot2)
library(ggpubr)
for (i in names(mtcars)[1:3]) {
  for (j in names(mtcars)[1:3]) {
    g=ggplot(mtcars, aes(x =!!sym(i), y = !!sym(j))) +
      geom_point(size = 3.5) +
      guides(fill=guide_legend(override.aes=list(shape=21))) +
      stat_cor(method = "pearson") +
      geom_smooth(method = lm, alpha = 0.1, color = "black")
    print(g)
  }
}

.... ....

Created on 2023-04-28 with reprex v2.0.2

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.