如何在同一个地方的闪亮应用中显示和隐藏不同的图

时间:2021-05-17 12:43:38

标签: r shiny

我正在编写一个 Shiny 应用程序。
在下面的示例中,我想:

  • 当我按下“按钮”时隐藏“plot1”。我试过 Shinyjs::hide() 没有成功
  • 能够在 HTML 页面的同一位置显示“plot1”或“plot2”图形。目前,这是不合适的,因为“plot1”和页面底部的标题h3之间有很大的空间。

我想要的是,当没有生成“plot2”时,只有“plot1”和没有空格的标题h3。当创建“plot2”时,“plot1”不再显示,“plot2”与网页上的“plot1”完全相同 希望说的够清楚。

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 个答案:

答案 0 :(得分:1)

为了使用 shinyjs 包,您必须在 UI 中包含 useShinyjs()。您可以使用 hidden 函数隐藏 UI 中的元素。

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")
  })
  
}