在闪亮的应用程序中基于一个 actionButton 隐藏和显示绘图

时间:2021-04-18 21:04:58

标签: r shiny

我有 shiny 应用程序,默认情况下在该应用程序下方显示一个绘图。当我点击 actionButton() 时它会隐藏它,但随后我想再次点击相同的 actionButton() 并显示它等等。

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      
      
      actionButton("hideshow_plot",
                   "HideShow plot")
    ),
    mainPanel(
      plotOutput(outputId = "car_plot")
      
    )
  )
)

server <- function(input, output) {
  showPlot <- reactiveVal(TRUE)

 
  
  observeEvent(input$hideshow_plot, {
    showPlot(FALSE) 
  })
  
  output$car_plot <- renderPlot({
    if (showPlot()){
      plot(cars)
    }
    else{
      
    }
  })
}

shinyApp(ui = ui, server = server)

2 个答案:

答案 0 :(得分:4)

你可以做到

  observeEvent(input$hideshow_plot, {
    showPlot(!showPlot()) 
  })

在每次点击时交替显示 TRUE/FALSE。

答案 1 :(得分:1)

考虑使用shinyjs

library(shiny)

ui <- fluidPage(
    shinyjs::useShinyjs(),
    sidebarLayout(
        sidebarPanel(
            actionButton("hideshow_plot",
                         "HideShow plot")
        ),
        mainPanel(
            plotOutput(outputId = "car_plot")

        )
    )
)

server <- function(input, output) {
    observeEvent(input$hideshow_plot, {
        shinyjs::toggle("car_plot")
    })

    output$car_plot <- renderPlot({
        plot(cars)
    })
}

shiny::shinyApp(ui, server)