Search code examples
rshinyalignmentreactiver-corrplot

How to control the position of r shiny plotOutput as it is expanded?


I'm building an app in which users can upload data and see a correlation plot of the numeric fields. As users can upload datasets of different sizes, I've made a slider so they can vary the size of the plot. Although this works, the bigger the plot is, the further away it gets - it scoots off to the right and down. So depending on the screen, the user might think the plot has failed! Is there a way of keeping the plot up near the rest of the content? I suspect padding is being added somewhere but can't find a solution - grateful for any advice?

Here's a mini version of my code - if you run it and increase the size you'll see the problem:

#UI
ui <- fluidPage(
           h4("Table 2 matrix"),
           sliderInput("Size2", "select size", min = 250, max = 3000, value = 250),
           uiOutput("Heatmap2", inline = TRUE),
)
#server side 
server <- function(input, output, session) {
  Table2 <- (mtcars)
  output$Heatmap2 <- renderUI({
    plotOutput("cor2plot", width = input$Size2, height = input$Size2)
  })
  
  output$cor2plot <- renderPlot({
    # calculate correlation matrix
    corrplot::corrplot(cor(dplyr::select_if(Table2, is.numeric)))
  })
}
  # Create Shiny app ----
  shinyApp(ui, server)

Solution

  • As pointed in the question itself, the output image has say 'embedded' margin that grows when the output size is bigger.

    I first tried with mar = c(0,0,0,0) but as pointed by @smartse it's set by default.

    I pushed the width / height argument at the renderPlot level. Note that I had to rewrite that part (remove the double-render and replace by an observer) otherwise you still get the expanding margin.

    #UI
    ui <- fluidPage(
      h4("Table 2 matrix"),
      sliderInput("Size2", "select size", min = 250, max = 3000, value = 250),
      plotOutput("cor2plot", inline = TRUE))
    
    
    #server side 
    server <- function(input, output, session) {
      
      # -- data
      Table2 <- (mtcars)
      
      # -- observe input
      observeEvent(input$Size2,
                   
                   # -- update output
                   output$cor2plot <- renderPlot(
                     
                     # calculate correlation matrix
                     corrplot::corrplot(cor(dplyr::select_if(Table2, is.numeric))), 
                     
                     width = input$Size2, height = input$Size2))}
    
    
    # Create Shiny app ----
    shinyApp(ui, server)