Reputation: 799
I am using the multiplot
function of this website
This function takes as argument an indefinite number of plots and plot them together. With the code below I can plot for example 4 plots together in 2 columns.
library(ggplot2)
n = 4
p = lapply(1:n, function(i) {
ggplot(data.frame(x = 1:10,y = rep(i,10)), aes(x = x, y = y)) +
geom_point()
})
multiplot(p[[1]],p[[2]],p[[3]],p[[4]],cols = 2)
How can I do if I have an undetermined number of plots n
?
I already tried things like
multiplot(p,cols = 2)
do.call(multiplot, list(p,cols = 2))
but it doesn't give the result that I want
Upvotes: 2
Views: 95
Reputation: 48221
With the second option you were also close:
do.call(multiplot, c(p, cols = 2))
does the job since
length(list(p, cols = 2))
# [1] 2
length(c(p, cols = 2))
# [1] 5
That is, list(p, cols = 2)
makes a list of two components: a list p
and an integer 2, while what you want is to extend p
by adding cols = 2
, and we need for that. (Somewhat not immediately obvious perhaps, but the title of ?c
does indeed say Combine Values into a Vector or List.)
Upvotes: 2