0

I have a function DisplayPlot which takes as an input a list of strings (which refers to columns in a dataframe). For instance, if list_string = c("string1","string2"), looping on the elements of list_string, I would like to display the two ggplots side-by-side.

So far what I have done in my function is storing the ggplots into a list:

for (i in 1:length(list_string){
p = ggplot(data=d, aes(x=d[,1], y=as.numeric(levels(d[,(i+1)]))[d[,(i+1)]], fill=d[,1])) +
  geom_bar(stat="identity") +
    guides(fill=FALSE) +
      labs(x = Y) + labs(y = paste("CP",list_X[i],"_per_",Y,sep = "")) 
graph[[length(graph) + 1]] <- p }

and return:

  return(list(graph=graph, along with some other information))

The issue is that if I want to use a function like grid.arrange, I need to write manually the names of the plots: grid.arrange(p1,p2,ncol=2) whereas in my case, this number may vary and are stored into a list (format that grid.arrange does not like).

Thank you very much in advance for your help, Clement

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
galzra
  • 31
  • 7
  • 5
    as a side-note, you should never use `[` or `$` inside `aes` – baptiste Apr 27 '16 at 08:53
  • why should I never use them inside aes? – galzra Apr 27 '16 at 14:34
  • Here's an illustration of what can go wrong: http://stackoverflow.com/a/32543753/471093 – baptiste Apr 27 '16 at 19:57
  • Hi, thanks for the example. In fact, I've done this because I did not find an other way to do it: in your example, x is known, x is a vector containing the values. In my case (because I looked for maximum scalability...and also because I'm not a pro R programmer!), the name of my columns do not contain values. So to have access to that name I'm using [ . If you see any solution I'll be very happy to use it – galzra Apr 28 '16 at 08:18
  • there are several ways to approach this without resorting to `[`; please post a new question with a self-contained minimal example (including mock-up data) – baptiste Apr 28 '16 at 10:05

2 Answers2

10
grid.arrange(grobs = graph)

or (historically, there wasn't always a grobs argument),

do.call(grid.arrange, graph)
baptiste
  • 75,767
  • 19
  • 198
  • 294
-2

I found an answer to my problem.

multiplot(plotlist=graph,col=length(list_string))

from the Rmisc package

galzra
  • 31
  • 7
  • You should say where you got the `multiplot` function from. It appears to be in a bunch of different packages, mostly drawn from [this page of the R Cookbook](http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/) – Ben Bolker Apr 28 '16 at 12:25