Home > Back-end >  Function to graph multiple X's at once
Function to graph multiple X's at once

Time:04-24

I'm trying to check the correlation of a bunch of variables and wanted to create a graph(s) of all the dependent variables on my response.

Price <- c(10,11,22,15,15)
Var1 <- c(2,3,12,5,17)
Var2 <- c(3,3,12,16,7)
Var3 <- c(2,5,2,5,18)
data <- data.frame(Var1,Var2,Var3,Price)

I was thinking something like this would work ;

variables <- c('Var1', 'Var2', 'Var3')
for (i in variables){
  plot <-  ggplot(data=data, aes(x = i, y=Price))  
    geom_point(shape=16, color="dodgerblue") 
    geom_smooth(method=lm, color='Black')
  print(plot)
}

But it only prints out the response for variable 3 without any values of x.

CodePudding user response:

As i in your loop is a character, you need to call it with get(i) in your ggplot:

for (i in variables){
  plot <-  ggplot(data=data, aes(x = get(i), y=Price))  
    geom_point(shape=16, color="dodgerblue") 
    geom_smooth(method=lm, color='Black')
  print(plot)
}

will work.

Two alternatives to have the 3 graphs together:

alternative 1

Long format, and facet_wrap:

library(tidyr)
pivot_longer(data,paste0("Var",1:3)) %>%
ggplot(aes(value,Price))  
  geom_point(shape=16, color="dodgerblue") 
  geom_smooth(method=lm, color='Black') 
  facet_wrap(~name)

enter image description here

second alternative

You could try to use the wonderful {patchwork} package also:

plot_list <- lapply(variables,function(i){
  ggplot(data=data, aes(x = get(i), y=Price))  
    geom_point(shape=16, color="dodgerblue") 
    geom_smooth(method=lm, color='Black') 
    labs(x = i)
})

library(patchwork)
wrap_plots(plot_list)

enter image description here

CodePudding user response:

par works in low-level plotting.

par(mfrow=c(1, 3))
with(data, lapply(names(data)[1:3], \(x) {
  plot(data[c(x, 'Price')]); abline(lm(Price ~ get(x)))
}))

enter image description here


Data:

data <- structure(list(Var1 = c(2, 3, 12, 5, 17), Var2 = c(3, 3, 12, 
16, 7), Var3 = c(2, 5, 2, 5, 18), Price = c(10, 11, 22, 15, 15
)), class = "data.frame", row.names = c(NA, -5L))
  •  Tags:  
  • r
  • Related