Home > OS >  shiny render plots side by side with size change with number of plots
shiny render plots side by side with size change with number of plots

Time:05-22

I want to render my plots in a way that the size of the plots change according to how many plots are displayed.

Here's my UI code:

 box(width=NULL, title = "Comparison", collapsible = TRUE, collapsed = TRUE, 
fluidRow(column(7, checkboxGroupInput("checkGroup", label = "Dataset to compare:", choices = list("1", "2", "3"), selected = "1"))),
fluidRow(column(12, uiOutput("plot_list")))
)

Here's my server code:

  output$plot_list <- renderUI({
    req(input$checkGroup)
    output = tagList()
    
    if(any(input$checkGroup %in% "1")){
      output[[1]] <- renderVisNetwork({makeVisnetwork(visOutputs[[1]]$coef_tbl)})
    }
    if(any(input$checkGroup %in% "2")){
      output[[2]] <- renderVisNetwork({makeVisnetwork(visOutputs[[2]]$coef_tbl)})
    }
    if(any(input$checkGroup %in% "3")){
      output[[3]] <- renderVisNetwork({makeVisnetwork(visOutputs[[3]]$coef_tbl)})
    }
    
    output
  })

This renders each plot taking up the whole row width of the dashboard after one another (vertically). I want it so that if I only check "1", then the whole row width is showing "1", but if I check "1" and "2" then the row is split into 2 and shows the plots side by side, and so on for "3".

I tried changing the last output line to do.call(flowLayout, output) but this doesn't split the page dynamically according to number of plots.

CodePudding user response:

library(shiny)
library(ggplot2)

ui <- fluidPage(
  br(),
  checkboxGroupInput(
    "cbg", "Plots", choices = list("a", "b", "c"), selected = "a"
  ),
  br(),
  uiOutput("plots")
)

server <- function(input, output, session){
  
  output[["plota"]] <- renderPlot({
    ggplot(
      iris, aes(x = Sepal.Length, y = Sepal.Width)
    )   geom_point()
  })

  output[["plotb"]] <- renderPlot({
    ggplot(
      iris, aes(x = Sepal.Length, y = Petal.Width)
    )   geom_point()
  })

  output[["plotc"]] <- renderPlot({
    ggplot(
      iris, aes(x = Petal.Length, y = Sepal.Width)
    )   geom_point()
  })
  
  output[["plots"]] <- renderUI({
    Plots <- list()
    if("a" %in% input[["cbg"]]){
      Plots <- c(Plots, list(plotOutput("plota")))
    }
    if("b" %in% input[["cbg"]]){
      Plots <- c(Plots, list(plotOutput("plotb")))
    }
    if("c" %in% input[["cbg"]]){
      Plots <- c(Plots, list(plotOutput("plotc")))
    }
    do.call(splitLayout, Plots)
  })
}

shinyApp(ui, server)
  • Related