0
votes

I'm coding a Shiny app.
In my example below, I would like:

  • hide "plot1" when I press the "button". I tried with shinyjs::hide() without success
  • be able to display the "plot1" or "plot2" graphic in the same place in the HTML page. Currently, this is not suitable, because there is a large space between "plot1" and the title h3 at the bottom of the page.

What I would like is that when "plot2" is not generated, there is only "plot1" and the title h3 with no spaces. And when "plot2" is created, "plot1" is no longer displayed and "plot2" is exactly at the same place as "plot1" on the web page Hoping to be clear enough.

library(shiny)
library(shinyjs)

# Global variables can go here
n <- 200


# Define the UI
ui <- bootstrapPage(
  numericInput('n', 'Number of obs', n),
  actionButton("button", "Validate second plot"),
  plotOutput('plot1'),
  plotOutput('plot2'),
  
  h3("Dashboard end...")
)


# Define the server code
server <- function(input, output) {

    
    output$plot1 <- renderPlot({
      hist(runif(isolate(input$n)),main="First histogram")
    })

  
  observeEvent(input$button, {
    
    shinyjs::hide("plot1")
    
    output$plot2 <- renderPlot({
      hist(runif(isolate(input$n)),main="Second histogram")
    })
    
  })
 
}

# Return a Shiny app object
shinyApp(ui = ui, server = server)

enter image description here

1

1 Answers

1
votes

In order to use the shinyjs package, you have to include useShinyjs() in your UI. You can hide an element in the UI with the hidden function.

ui <- bootstrapPage(
  useShinyjs(),
  numericInput('n', 'Number of obs', n),
  actionButton("button", "Validate second plot"),
  plotOutput('plot1'),
  hidden(plotOutput('plot2')),
  h3("Dashboard end...")
)


server <- function(input, output) {
  
  output$plot1 <- renderPlot({
    hist(runif(isolate(input$n)),main="First histogram")
  })

  output$plot2 <- renderPlot({
    hist(runif(isolate(input$n)),main="Second histogram")
  })
    
  observeEvent(input$button, {
    hideElement("plot1")
    showElement("plot2")
  })
  
}