jslefche
jslefche

Reputation: 4599

Looping over ggplot2 with columns

I am attempting to loop over both data frames and columns to produce multiple plots. I have a list of data frames, and for each, I want to plot the response against one of several predictors.

For example, I can easily loop across data frames:

df1=data.frame(response=rpois(10,1),value1=rpois(10,1),value2=rpois(10,1))
df2=data.frame(response=rpois(10,1),value1=rpois(10,1),value2=rpois(10,1))

#Looping across data frames
lapply(list(df1,df2), function(i) ggplot(i,aes(y=response,x=value1))+geom_point())

But I am having trouble looping across columns within a data frame:

lapply(list("value1","value2"), function(i) ggplot(df1,aes_string(x=i,y=response))+geom_point())

I suspect it has something to do with the way I am treating the aesthetics.

Ultimately I want to string together lapply to generate all combinations of data frames and columns.

Any help is appreciated!


EDIT: Joran has it! One must put the non-list responses in quotes when using aes_string

lapply(list("value1","value2"), function(i) ggplot(df1,aes_string(x=i,y="response"))+geom_point())

For reference, here is stringing the lapply functions to generate all combinations:

lapply(list(df1,df2), function(x)
  lapply(list("value1","value2"), function(i) ggplot(x,aes_string(x=i,y="response"))+geom_point() ) )

Upvotes: 4

Views: 4307

Answers (1)

bdemarest
bdemarest

Reputation: 14667

Inside of aes_string(), all variables need to be represented as character. Add quotes around "response".

lapply(list("value1","value2"), 
       function(i) ggplot(df1, aes_string(x=i, y="response")) + geom_point())

Upvotes: 7

Related Questions