在闪亮的应用程序中使用相同的 actionButton() 在 2 个以上的图之间切换

时间:2021-04-21 14:00:00

标签: r shiny

我有下面的 shiny 应用程序,我想在其中使用相同的 actionButton() 在 3 个图之间切换。

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      actionButton("exc", "Exchange")
    ),
    mainPanel(
      uiOutput(outputId = "plot")
    )
  )
)

server <- function(input, output) {
  
  excplot <- reactiveVal(TRUE)
  
  observeEvent(input$exc, {
    excplot(!excplot())
  })
  
  
  output[["bar1"]]<-renderPlot({
    if (excplot()) {
      fig1 <- plot(iris
      ) 
      
      fig1 
    }else {
      fig1 <- plot(mtcars
      ) 
      
      fig1 
    }
    #else {
     # fig1 <- plot(iris3
      #) 
      
      #fig1 
    #}
    
  })
  
  output$plot <- renderUI({
    plotOutput("bar1")
  })
}
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

这样做的一个好方法(通过按一个按钮来遍历 3 个选项以在它们之间切换)是首先了解您可以通过 input 中的 server 访问操作按钮的值部分。每次用户在您分享的应用中按下按钮,input$exc 的值都会增加 1。

您可以利用这一点来意识到您可以根据按钮的值和 mod (%%) 运算符来确定要显示的图。因此,input$exc %% 3 可用于循环遍历等于 1、2 和 0 的值。将该值映射到您想要显示的图,您就可以按照您的描述进行操作。

在下面的应用中,您会看到我添加了一个 textOutput() UI 元素,用于显示按钮的当前值,以便您可以看到发生了什么。

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      actionButton("exc", "Exchange"),
      textOutput('button_value')
    ),
    mainPanel(
      uiOutput(outputId = "plot")
    )
  )
)

server <- function(input, output) {
  
  output[["bar1"]]<-renderPlot({
    if (input$exc %% 3 == 1)
      plot(iris)
    else if (input$exc %% 3 == 2)
      plot(mtcars)
    else
      plot(CO2)
  })
  
  output$button_value <- renderText(paste('Current Value of Button:', input$exc))
  
  output$plot <- renderUI({
    plotOutput("bar1")
  })
}
shinyApp(ui = ui, server = server)

值得注意的是,您不需要设置 reactiveVal 或使用 observeEvent() 或设置另一个观察者来完成这项工作。 input$exc 是响应式的,因此无论如何都会在您点击按钮时更新。