3
votes

I am using shiny dashboard for making an app. What I want is that when you run this app then plot size will adjust automatically according to windows size .I have tried this code for automatically adjust height and weight of a plot according to windows size..

Problem :

The width of the plot is changing its size according to the app window size by using following code but the height isn't ?

sidebar <- dashboardSidebar(
sidebarMenu(menuItem("plot",tabName = "plot"),
  menuItem("Plot1",tabName = "Plot1"),
)

body <- dashboardBody(
tabitems(
tabItem(tabName = "plot", 
   box( width = "100%" , height = "100%", solidHeader = FALSE, status = "primary",
     plotOutput("plot"))
)
tabItem(tabName = "plot1", 
   box( width = "100%" , height = "100%", solidHeader = FALSE, status = "primary",
     plotOutput("plot1")))
1

1 Answers

1
votes

Is seems like if the box height is initialized as 100% in dashboardBody it wont re-size to the page, to fix this we can re-size the box manually from Javascript.

library(shiny)
library(shinydashboard)

ui <-dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
  ),
  dashboardBody(
    tags$head(
      tags$script(
        HTML("
          window.onload = function() {
            resize();
          }
          window.onresize = function() {
            resize();
          }
          Shiny.addCustomMessageHandler ('triggerResize',function (val) {
            window.dispatchEvent(new Event('resize'));
          });
          function resize(){
            var h = window.innerHeight - $('.navbar').height() - 150; // Get dashboardBody height
            $('#box').height(h); 
          }"
        )
      )
    ),
    box( id ="box",
         width  = 12, 
         height = "100%",
         solidHeader = FALSE, 
         status = "primary",
         plotOutput("plot1",inline=F,width="100%",height="100%")
    ),
    actionButton("plot","plot")
  )
)

server <- shinyServer(function(input, output, session) {
  observeEvent(input$plot,{
    session$sendCustomMessage (type="triggerResize", 1)
    output$plot1 <- renderPlot({plot(runif(100),runif(100))})
  })
})

shinyApp(ui = ui, server = server)

Alternatively you can modify the Javascript like:

HTML("
  $(document).ready(function(){
    resize();
  })
  function resize(){
    var h = window.innerHeight - $('.navbar').height() - 150; // Get dashboardBody height
    $('#box').height(h); 
  }"
    ) # END html

And skip the call to Javascript from the observer.

Is this of any help?