Chapo
Chapo

Reputation: 2543

show an unknown number of graphs in a grid RShiny

I have looked at all the solutions on SO using grid.arrange but it doesn't really achieve what I want.

Let's assume I have a list of grobs that are generated within a reactive environment in RShiny.

I would like to create a mainPanel where those graphs are on 2 columns (until that point, it's all feasible with grid.arrange) but where each line corresponds to a fluidRow element.

A barebone example of this would be

ui <- fluidPage(

    titlePanel("TEST"),
    sidebarPanel(width=3,
        actionButton(inputId = 'launchCalcButton',label = 'Launch Calc')
    ),
    mainPanel(
        uiOutput("resultsPlotUI")
    )
)

server <- function(input,output){

    graphsList <- eventReactive(input$launchCalcButton, {
        a <- lapply(1:10,function(i){
            return(
                ggplot(data = data.frame(a=rnorm(10),b=rnorm(10)),aes(x=a,y=b))
                +geom_point()
            )
        })
        return(a)
    })
    output$resultsPlot <- renderPlot({
        do.call(grid.arrange,c(graphsList(),ncol=2))
    })

    output$resultsPlotUI <- renderUI({
        fluidRow(
            column(12,
                plotOutput(
                    outputId = 'resultsPlot'
                )
            )
        )
    })
}

app = shinyApp(ui,server)
runApp(app)

All the graphs end up squeezed into one single line whereas I would want them to be split between lines.

Screenshot

Upvotes: 0

Views: 244

Answers (1)

Mal_a
Mal_a

Reputation: 3760

You just need to set up height parameter for the plotOutput:

library(shiny)
library(gridExtra)
ui <- fluidPage(

  titlePanel("TEST"),
  sidebarPanel(width=3,
               actionButton(inputId = 'launchCalcButton',label = 'Launch Calc')
  ),
  mainPanel(
    uiOutput("resultsPlotUI")
  )
)

server <- function(input,output){

  graphsList <- eventReactive(input$launchCalcButton, {
    a <- lapply(1:10,function(i){
      return(
        ggplot(data = data.frame(a=rnorm(10),b=rnorm(10)),aes(x=a,y=b))
        +geom_point()
      )
    })
    return(a)
  })
  output$resultsPlot <- renderPlot({
    l <- length(graphsList())/2
    print(l)
    do.call(grid.arrange,c(graphsList(),ncol=2))
  })

  output$resultsPlotUI <- renderUI({
    fluidRow(
      column(12,
             plotOutput(
               outputId = 'resultsPlot', height = 600
             )
      )
    )
  })
}

app = shinyApp(ui,server)
runApp(app)

Exactly in this place:

 output$resultsPlotUI <- renderUI({
    fluidRow(
      column(12,
             plotOutput(
               outputId = 'resultsPlot', height = 600
             )
      )
    )
  })

I have set it up to 600 px (height = 600) but you can choose whatever you want.

enter image description here

Upvotes: 1

Related Questions