d_w
d_w

Reputation: 85

How to make plotly work with shiny and gridExtra?

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"

Upvotes: 5

Views: 1666

Answers (1)

Conor Neilson
Conor Neilson

Reputation: 1091

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)

Upvotes: 6

Related Questions