Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

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

$
0
0

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?


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>