Reputation: 21
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?
Upvotes: 0
Views: 45
Reputation: 1800
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
Upvotes: 0