Miguel Rayon Gonzalez
Miguel Rayon Gonzalez

Reputation: 1653

How to use for function to construct a panel of ggplot2 plots in R

I am a beginner trying to build a multiple plots in ggplot2. Using the mtcars dataset in R

library(datasets)
data (mtcars)
library (ggplot2)
## convert to factor some variables to avoid problems
factors<-c(2,9,10,11)
mtcars[,factors]<-lapply(mtcars[,factors],factor)

I want to plot mpg vs all the other variables except the am variable that is plot in colour in each plot. Each plot looks like this:

g1<- ggplot(mtcars, aes(x=mpg, y=cyl, color=am)) + geom_point(shape=1)
g2<- ggplot(mtcars, aes(x=mpg, y=disp, color=am)) + geom_point(shape=1)
g3...

Only the y axis changes from one plot to the other. I have done the plots form g1 to g9, y axis being any of the following:

variables<- c ("cyl","disp","hp","drat","wt","qsec","vs","gear","carb") 

I am sure there must be a more elegant way to generate all 9 plots, but cannot figure out Any help?

Upvotes: 0

Views: 68

Answers (1)

lukeA
lukeA

Reputation: 54247

If you want the plots in g1...g_n:

g <- lapply(variables, function(var) {
  ggplot(mtcars, aes_string(x="mpg", y=var, color="am")) + geom_point(shape=1) 
})
names(g) <- paste0("g", seq(g))
list2env(g, .GlobalEnv)

Upvotes: 0

Related Questions