Search code examples
rggplot2gridextragrob

Conditional Graph in grid.arrange


Is there a way to use a structure like

grid.arrange(
    ifelse(somecondition,graph1,graph2),
    ifelse(somecondition2,graph3,graph4),
    ncol=2
)

where graphX is either a plot (created with ggplot2) or a grob defined previously. It looks like ifelse evaluates the grob object to something else (a dataframe ?) before printing so grid.arrange doesn't get the right input to work properly.

I also tried to store all the graph objects in a collection and use that within grid.arrange but coudn't get a proper data structure to work nicely.


Solution

  • use if() ... else ..., not ifelse,

    p1 = qplot(1,1)
    p2 = qplot(1,2)
    p3 = qplot(1,3)
    p4 = qplot(1,4)
    
    grid.arrange(
        if(1 == 2) p1 else p2,
        if(3 == 3) p3 else p4,
        ncol=2
    )
    

    If you want to store them in a list first,

    pl = list(if(1 == 2) p1 else p2, if(3 == 3) p3 else p4)
    grid.arrange(grobs=pl, ncol=2)