In R shiny app, how to plot two ggplot objects arranged by “arrangeGrob()”?

600 views
Skip to first unread message

Yaohui Zeng

unread,
Jul 27, 2016, 2:50:34 PM7/27/16
to Shiny - Web Framework for R
Dear R-Shiny users,

I have a plot which consists of ggplot objects and is arranged by following code:

## ggplot shared legend
grid_arrange_shared_legend
<- function(..., position = c("bottom", "right")) {
 
  plots
<- list(...)
  position
<- match.arg(position)
  g
<- ggplotGrob(plots[[1]] + theme(legend.position=position))$grobs
  legend
<- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lheight
<- sum(legend$height)
  lwidth
<- sum(legend$width)
  gl
<- lapply(plots, function(x) x + theme(legend.position="none"))
 
  combined
<- switch(position,
                     
"bottom" = arrangeGrob(do.call(arrangeGrob, gl),
                                            legend
,
                                            ncol
= 1,
                                            heights
= unit.c(unit(1, "npc") - lheight, lheight)),
                     
"right" = arrangeGrob(do.call(arrangeGrob, gl),
                                           legend
,
                                           ncol
= 2,
                                           widths
= unit.c(unit(1, "npc") - lwidth, lwidth)))
#   combined
  grid
.draw(combined)
}

It works nicely in general. However, it doesn't work in a Shiny App with renderPlot() like following:

  output$main.plot <- renderPlot({

    fit
<- res$main.fit
 
   
# p1, p2 are two ggplot objects. It works fine if I just plot only one.
    p1
<- get_ggplot(fit)
    p2
<- get_ggplot(fit)

    grid_arrange_shared_legend
(p1, p2)

 
})



Could anyone clarify to me what the problem is and how I can fix it? Thank you very much!


Yaohui



Robin Cura

unread,
Jul 27, 2016, 6:13:03 PM7/27/16
to Yaohui Zeng, Shiny - Web Framework for R
Hi,

I thought it had something to do with grid.draw being called in a function, but just tried it and it works, see this example : https://gist.github.com/RCura/2e92f7659a37c0aad9b95cd210fa517e

So, I think your error is with your plots p1 and p2 :)

HTH,

Robin

--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/shiny-discuss/49a14b3a-a0c2-4d10-a529-98ec6bac2c2f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Yaohui Zeng

unread,
Jul 28, 2016, 9:56:17 PM7/28/16
to Robin Cura, Shiny - Web Framework for R
​Thank you, Robin. It worked out!
Reply all
Reply to author
Forward
0 new messages