luciano
luciano

Reputation: 13850

Function to make multiple scatterplots

I have this dataframe:

set.seed(50)
data <- data.frame(age=c(rep("juv", 10), rep("ad", 10)),
                   sex=c(rep("m", 10), rep("f", 10)),
                   size=c(rep("large", 10), rep("small", 10)),
                   length=rnorm(20),
                   width=rnorm(20),
                   height=rnorm(20))

Using this dataframe, I need to make 9 scatterplots, that plot each continuous variable against each factor variable. So I need to make these scatterplots:

library(ggplot2)

ggplot(data, aes(length, width, group=age, colour=age)) + geom_point()
ggplot(data, aes(length, height, group=age, colour=age)) + geom_point()
ggplot(data, aes(width, height, group=age, colour=age)) + geom_point()

ggplot(data, aes(length, width, group=sex, colour=sex)) + geom_point()
ggplot(data, aes(length, height, group=sex, colour=sex)) + geom_point()
ggplot(data, aes(width, height, group=sex, colour=sex)) + geom_point()

ggplot(data, aes(length, width, group=size, colour=size)) + geom_point()
ggplot(data, aes(length, height, group=size, colour=size)) + geom_point()
ggplot(data, aes(width, height, group=size, colour=size)) + geom_point()

However, I want to be able to make these 9 scatterplots using a function. Something like this:

makeScatterplots <- function(x.variable, y.variable, my.factor){

  ggplot(dataframe, aes(x.variable, y.variable, group=my.factor, colour=my.factor)) + geom_point()

}

How can I make an function, which takes the x variables, y variables and grouping factors, that will compute these 9 scatterplots?

Upvotes: 2

Views: 2771

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98579

Use aes_string() inside ggplot() and supply x.variable and y.variable as names (characters), and also use print() around ggplot() call.

makeScatterplots <- function(dataframe,x.variable, y.variable, my.factor){
  print(ggplot(dataframe, aes_string(x=x.variable,y= y.variable, 
                     group=my.factor, colour=my.factor)) + geom_point())  
}

makeScatterplots(data,"length","width","age")

UPDATE

Merging together this and previous OP question

This function will produce all possible combination of x, y and factor variables.

makeScatterplots <- function(dataframe,x.variable, y.variable, my.factor){
  gg<-expand.grid(x.variable,y.variable,my.factor)
  gg<-data.frame(lapply(gg, as.character), stringsAsFactors=FALSE)
  apply(gg,1,function(x) ggplot(data,aes_string(x=x[1],y=x[2],color=x[3]))+geom_point())
}

Upvotes: 4

Related Questions