问题描述:

I took the second example from http://rstudio.github.io/shinydashboard/get_started.html and the problem is that for some types of rendering the scaling is not good.

Dashboard opened:

Dashboard closed:

Dashboard closed and open console(this time it scales the plot as it should have done from begining)

Is it possible to rerender the plot when the dashboard is closed/opened?

网友答案:

You can force a resize event on the window when the dashboard open/close button is clicked by using jQuery to bind a function to the button like this:

library(shinydashboard)

ui <- dashboardPage(

  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    tags$script('
      // Bind function to the toggle sidebar button
      $(".sidebar-toggle").on("click",function(){
        $(window).trigger("resize"); // Trigger resize event
      })'
    ),

    # Boxes need to be put in a row (or column)
    fluidRow(
      box(plotOutput("plot1", height = 250)),

      box(
        title = "Controls",
        sliderInput("slider", "Number of observations:", 1, 100, 50)
      )
    )
  )
)

server <- function(input, output, session) {
  set.seed(122)
  histdata <- rnorm(500)

  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider)]
    hist(data)
  })
}

shinyApp(ui, server)

If you don't want to force a re-size event on all elements you can recreate the plotOutput by using shiny::uiOutput and shiny::renderUI functions each time the sidebar is toggled.

library(shinydashboard)

ui <- dashboardPage(

  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    tags$script('
      // Bind function to the toggle sidebar button
      $(".sidebar-toggle").on("click",function(){
        // Send value to Shiny 
        Shiny.onInputChange("toggleClicked", Math.random() );
      })'
    ),

    # Boxes need to be put in a row (or column)
    fluidRow(
      #box(plotOutput("plot1", height = 250)),
      box(uiOutput('plotUi')),

      box(
        title = "Controls",
        sliderInput("slider", "Number of observations:", 1, 100, 50)
      )
    )
  )
)

server <- function(input, output, session) {
  # Helper function to create the needed ui elements
  updateUI <- function(){
    output$plotUi <- renderUI({
      plotOutput("plot1", height = 250)
    })
  }

  # Plot data to plotOutput
  updatePlot <- function(){
    output$plot1 <- renderPlot({
      hist( data() )
    })
  }

  set.seed(122)
  histdata <- rnorm(500)

  # Initialize UI and create plotOutput
  updateUI()
  updatePlot()

  # Create a reactive dataset
  data <- eventReactive(input$slider,{
    histdata[seq_len(input$slider)]
  })

  # This is triggered when the toggle dashbord button is clicked
  # this is achived by the javascript binding in the ui part
  observeEvent(input$toggleClicked,{
    updateUI()
    updatePlot()
  })
}

shinyApp(ui, server)
相关阅读:
Top