Shiny: Dynamic Number of Output Elements/Plots

Solution 1:

Inspired from this, you could do:

ui.R

shinyUI(pageWithSidebar(            
        headerPanel("Dynamic number of plots"),            
        sidebarPanel(
                selectInput(inputId = "choosevar",
                            label = "Choose Cut Variable:",
                            choices = c("Nr. of Gears"="gear", "Nr. of Carburators"="carb"))
        ),            
        mainPanel(
                # This is the dynamic UI for the plots
                uiOutput("plots")
        )
))

server.R

library(googleVis)
shinyServer(function(input, output) {
        #dynamically create the right number of htmlOutput
        output$plots <- renderUI({
                plot_output_list <- lapply(unique(mtcars[,input$choosevar]), function(i) {
                        plotname <- paste0("plot", i)
                        htmlOutput(plotname)
                })

                tagList(plot_output_list)
        }) 

        # Call renderPlot for each one. Plots are only actually generated when they
        # are visible on the web page. 


        for (i in 1:max(unique(mtcars[,"gear"]),unique(mtcars[,"carb"]))) {
                local({
                        my_i <- i
                        plotname <- paste0("plot", my_i)

                        output[[plotname]] <- renderGvis({
                                data <- mtcars[mtcars[,input$choosevar]==my_i,]
                                if(dim(data)[1]>0){
                                gvisColumnChart(    
                                        data, xvar='hp', yvar='mpg' 
                                )}
                                else NULL
                        })  
                })
        }

})

It basically creates htmlOutput plots dynamically and binds the googleVis plots when there is data in the subset.