How to make plotly work with shiny and gridExtra?
Asked Answered
L

1

5

I'm using R shiny would like to put several ggplotly plots side by side with the help of gridExtra.

One plot (without gridExtra) works just fine:

library(shiny)
library(plotly)

u <- fluidPage(plotlyOutput(outputId = "myplots"))

s <- function(input, output) {
  pt1 <- reactive({
    ggplotly(qplot(42))
  })

  output$myplots <- renderPlotly({
    pt1()
  })
}

shinyApp(u, s)

Now when I try to add one more plot via gridExtra, it refused to work:

library(shiny)
library(plotly)
library(gridExtra)

u <- fluidPage(plotlyOutput(
  outputId = "myplots"
))

s <- function(input, output){
  pt1 <- reactive({
    ggplotly(qplot(42))
  })

  pt2 <- reactive({
    ggplotly(qplot(57))
  })

  output$myplots <- renderPlotly({
    grid.arrange(pt1(), pt2(),
                 widths = c(1, 1),
                 ncol = 2)
  })
}

shinyApp(u, s)

giving me

Error in gList: only 'grobs' allowed in "gList"

Leptosome answered 29/5, 2018 at 8:11 Comment(1)
use subplot instead of grid.arrangeTransarctic
U
6

Rather than using grid.arrange to pass many plots to a single plotlyOutput, it would be better to set up your ui to accept several plots and then pass them individually. For example, your ui and server could look like this

Note that defining columns like this uses Bootstrap theming, which means the widths need to add to 12. Thats why I've defined each column to have a width of 6 - each will naturally fill half the page

library(shiny)
library(plotly)
library(gridExtra)

u <- fluidPage(
  fluidRow(
    column(6, 
           plotlyOutput("pt1")),
    column(6, 
           plotlyOutput("pt2"))
  )
)

s <- function(input, output){
  output$pt1 <- renderPlotly({
    ggplotly(qplot(42))
  })

  output$pt2 <- renderPlotly({
    ggplotly(qplot(57))
  })

}

shinyApp(u, s)
Unpack answered 29/5, 2018 at 9:23 Comment(2)
Whoever downvoted this, you could at least leave a comment explaining why. It's zero help to anyone if you just downvote with no explanation. It's a reasonable answer to a well asked questionUnpack
how do you increase the width?Livi

© 2022 - 2025 — McMap. All rights reserved.