0
votes

Im trying to use the multiplot function (http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/) to arrange several plots in one diagram. The following example, taken from http://rstudio-pubs-static.s3.amazonaws.com/2852_379274d7c5734f979e106dcf019ec46c.html, works fine:

plots <- list()  # new empty list
for (i in 1:6) {
    p1 = qplot(1:10, rnorm(10), main = i)
    plots[[i]] <- p1  # add each plot into plot list
}
multiplot(plotlist = plots, cols = 3)

However, my code doesn't:

dataset <- data.frame(x=c(1,2,3,4,5,6), y1=c(1,4,6,8,10,12), y2=rnorm(6))
plots <- list()
for (i in 1:2){
  plots[[i]] <- ggplot(dataset) + geom_point(aes(x=dataset[,1], y=dataset[,i+1]))
}

multiplot(plotlist = plots, cols=2)

Somehow it has to do with how the plot objects are assigned to the list, for when I do

a <- ggplot(dataset) + geom_point(aes(x=dataset[1], y=dataset[2]))
b <- ggplot(dataset) + geom_point(aes(x=dataset[1], y=dataset[3]))
multiplot(a,b)

everything works as expected. Also multiplot(plotlist=list(a,b)) works fine.

I fail to recognize what the relevant differences are. Can anyone help?

Many thanks,

Enno

2

2 Answers

1
votes

huh. Fascinating.

it turns out that i inside the ggplot call doesn't get evaluated until the plot is actually created:

plots <- list()
i <- 1
plots[[i]] <- ggplot(dataset) + geom_point(aes(x=dataset[,1], y=dataset[,i+1]))

draws your plot with y1:

plots[[1]]

change i

i <- 2

and now your list suddenly renders your plot with y2:

plots[[1]]
0
votes

It has to with setting the dataset into aes I think. I usually call the variable directly which seems to work:

plots <- list()
for (i in 1:2){
  p1 <- ggplot(dataset,aes_string(x=names(dataset)[1], y=names(dataset)[i+1])) + geom_point()
  plots[[i]] <- p1
}

multiplot(plotlist = plots, cols=2)