marc
marc

Reputation: 13

several plots (scatter plot of a specific variable vs other variables) in R

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)

Upvotes: 1

Views: 1428

Answers (1)

neilfws
neilfws

Reputation: 33802

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

Upvotes: 1

Related Questions