Home > Software engineering >  Keep the figure size at full scale for multiple figures
Keep the figure size at full scale for multiple figures

Time:09-22

The following code allows to have multiple user-defined graphs using patchwork library. However, as the number of figures increases, the size becomes smaller. is there any way to keep the size of each figure at predefined heights and width or keep the total height at 100%?

library(dplyr)
library(ggplot2)
library(shiny)
library(patchwork)

plt_func <- function(x,y){
  plt_list <- list()
  for (X_var in x){
    plt_list[[X_var]] <- mtcars %>% ggplot(aes_string(X_var, y)) 
      geom_point()   
      labs(x = X_var, y = y)
  }
  
  if (length(plt_list) == 1) {
    return(plt_list[[1]])
  } else {
    patchwork::wrap_plots(plt_list, ncol = min(length(plt_list), 2)) %>% print(.)
  }
}


ui <- fluidPage(
  sidebarLayout(
    sidebarPanel( 
      selectInput(inputId = "dataset",
                  label = "Choose a dataset:",
                  choices = c("mtcars")),
      selectizeInput(inputId = "x",label = "X", choices = names(mtcars), multiple = T),
      selectInput(inputId = "y",label = "Y", choices = names(mtcars),multiple = F),
      selectInput(inputId = "t",label = "Treatment", choices = names(mtcars),multiple = F),
                 actionButton("plot", label = "Plot")),
    mainPanel(
      plotOutput("plots")
      
    )
  )
)

server <- function(input, output, session) {
  
  observeEvent(input$plot, {
    req(input$x, input$y)
    x <- input$x
    y <- input$y
    
    output$plots <- renderPlot({
        
        plt_func(x,y)
    
    
    })
  
    
})
  

}

shinyApp(ui, server)

figure size when there are two figures:

enter image description here

figure size when there are 6 figures:

enter image description here

CodePudding user response:

The default height is 400px. You can change it with the height argument of renderPlot:

  observeEvent(input$plot, {
    req(input$x, input$y)
    x <- input$x
    y <- input$y
    nplots <- (length(x)   1L) %/% 2L
    
    output$plots <- renderPlot({
      plt_func(x,y)
    }, height = nplots * 400)
    
  })

But it is not recommended to define an output slot inside an observer. It's better to do like this:

server <- function(input, output, session) {
  
  output[["plots"]] <- renderPlot({
    req(input$x, input$y)
    x <- input$x
    y <- input$y
    plt_func(x,y)
  }, height = exprToFunction(400 * ((length(input[["x"]])   1L) %/% 2L)) %>%
    bindEvent(input[["plot"]])
  
}

We need exprToFunction because input[["x"]] is a reactive variable.

  • Related