Electrino
Electrino

Reputation: 2900

How to write a function to loop through variables and plot using ggplot

I'm having problems figuring out how to loop through variables in a data frame and plot them using ggplot. An example of my data is below:

head(myData,2)

          x1        x2      yhat        x11        x3    yhat1        x12
1 -0.8523122 -2.737223 -6.562228 -0.8523122 -1.450288 0.464739 -0.8523122
2 -0.5649950 -2.737223 -6.562228 -0.5649950 -1.450288 0.464739 -0.5649950
         x4     yhat2       x21       x31      yhat3
1 -1.267759 -4.624147 -2.737223 -1.450288 -0.6858007 
2 -1.267759 -4.624147 -2.267001 -1.450288 -0.6858007 

What I'm trying to do is to use geom_raster to plot each pair of variables (i.e., [x1,x2],[x11,x3],etc) and use the corresponding yhat as the fill value.

For example, if I were to plot everything manually I'd do something like:

p<-ggplot(myData, aes(x = x1, y = x2)) + geom_raster(aes(fill = yhat))
pp<-ggplot(myData, aes(x = x11, y = x3)) + geom_raster(aes(fill = yhat1))
ppp<-ggplot(myData, aes(x = x12, y = x4)) + geom_raster(aes(fill = yhat2))
pppp<-ggplot(myData, aes(x = x21, y = x31)) + geom_raster(aes(fill = yhat3))

grid.arrange(p, pp, ppp, pppp, ncol = 2)

But I'm trying to write a function that will loop through the data frame and plot the graphs. I tried to adapt the code from a different question here but I can't make it work for me.

Any suggestions as to how I would achieve this for my data?

Upvotes: 1

Views: 100

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

One way would be to split data in every 3 columns and apply the code to each list.

library(gridExtra)
library(tidyverse)
library(rlang)

 temp <- split.default(df, gl(ncol(myData)/3, 3)) %>%
      map(~{
      x <- syms(names(.))
      ggplot(., aes(x = !!x[[1]], y = !!x[[2]])) + geom_raster(aes(fill = !!x[[3]]))
     })
grid.arrange(grobs = temp)  

enter image description here

data

Applied this on limited data of 2 rows.

myData <- structure(list(x1 = c(-0.8523122, -0.564995), x2 = c(-2.737223, 
-2.737223), yhat = c(-6.562228, -6.562228), x11 = c(-0.8523122, 
-0.564995), x3 = c(-1.450288, -1.450288), yhat1 = c(0.464739, 
0.464739), x12 = c(-0.8523122, -0.564995), x4 = c(-1.267759, 
-1.267759), yhat2 = c(-4.624147, -4.624147), x21 = c(-2.737223, 
-2.267001), x31 = c(-1.450288, -1.450288), yhat3 = c(-0.6858007, 
-0.6858007)), class = "data.frame", row.names = c("1", "2"))

Upvotes: 1

Related Questions