Shiny: Dynamic Number of Output Elements/Plots

前端 未结 2 992
傲寒
傲寒 2020-12-03 11:06

I want to make a reactive display, that displays a different number of plots depending on which value of the input selector is chosen. In the case of the mt

相关标签:
2条回答
  • 2020-12-03 11:33

    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.

    0 讨论(0)
  • 2020-12-03 11:43

    Have you tried making a total of 9 (6+3) conditionalPanels? If yes, have you tried 3 naked output panels that have conditionals inside them to switch between the plots, and 3 additional conditionalPanels for the non-overlapped plots?

    Another way might be to make a single output panel with an internal conditional, and then stack your 3 or 6 plots into a single plot ala

    if(cond1) {
       par(mfrow=c(3,1))
       plot1
       plot2
       plot3
    } else {
       par(mfrow=c(3,2))
       plot1
       plot2
       plot3
       plot4
       plot5
       plot6
    }
    
    0 讨论(0)
提交回复
热议问题