Making multiple plots with mapply

1.9k views Asked by At

I made the following dataframe df:

V1 <- 1:10
V2 <- 11:20
V3 <- 21:30
V4 <- 31:40
df <- data.frame(V1,V2,V3,V4)

I also made a function which should make a simple scatterplot based on the arguments var1 and var2.

 ScatterPlot <- function(var1, var2) {
     ggplot(data = df,
     aes(x = var1, y = var2)),
     environment = environment() +
     geom_point()
 }

I only want 2 specific scatterplots for the following combinations of variables: v1-v2 and v3-v4.

I thought mapply would come in handy here, looping over different combinations of variables.

mapply(FUN = ScatterPlot,
       var1 = c(V1, V3),
       var2 = c(V2, V4))

I just expected 2 plots but this is what I got instead:

enter image description here

1

There are 1 answers

3
Cath On BEST ANSWER

I think the problem came from the fact that the function is looking for a variable inside df named "var1". I don't know ggplots enough to circumvent this problem but, with base R plot, you can do:

baseplot <- function(var1, var2){
    plot(df[,var1], df[,var2], pch=19)
}
par(mfrow=c(1, 2))
mapply(baseplot, c("V1", "V3"), c("V2", "V4"))

enter image description here

EDIT
With ggplotand putting parameter environment=environment(), adding print and using variable names (between quotes) seems to work:

 ScatterPlot <- function(var1, var2) {
     print(ggplot(data = df,
     aes(x = df[,var1], y = df[,var2]),
     environment = environment()) +
     geom_point())
 }

mapply(ScatterPlot, var1=c("V1", "V3"), var2=c("V2", "V4"))