0
votes

How can I modify this code to have all plots together and on one page(loop function)? In my real data set, I want to have the scatter plot between the dependent variable and 10 independent variables. The scatter plot between the dependent variable and each IV separately.

plot(rock$area, rock$peri)
plot(rock$area, rock$shape)
plot(rock$area, rock$perm)
1
Before the three plots, type par(mfrow=c(1,3))G5W
Probably best not to use the function name plot for a variable name.neilfws

1 Answers

1
votes

Since you tagged your question with ggplot2, I'll assume that you are interested in a ggplot2 solution.

rock <- data.frame(area  = sample(1:100, 10, replace = TRUE),
                   peri  = sample(1:100, 10, replace = TRUE),
                   shape = sample(1:100, 10, replace = TRUE), 
                   perm  = sample(1:100, 10, replace = TRUE))

Now we can make the data tidy (a column for y variable names, another column for y variable values) and use facets to create separate plots per y variable.

library(tidyr)
library(ggplot2)
rock %>% 
  gather(yvar, val, -area) %>% 
  ggplot(aes(area, val)) + 
    geom_point() + 
    facet_grid(yvar ~ .)

enter image description here