【问题标题】:R Shiny - How do I toggle between two different plots using an action buttonR Shiny - 如何使用操作按钮在两个不同的图之间切换
【发布时间】:2020-11-12 14:38:34
【问题描述】:

在我的应用程序中,我希望 plot1 默认显示,然后如果单击操作按钮,让 plot2 替换 plot1。如果再次单击,则恢复为 plot1,依此类推。


server <- function(input, output, session) {
     plot1 <- (defined here)
     plot2 <- (defined here)
  
     which_graph <- reactive({
        if (input$actionbutton == 1) return(plot1)
        if (input$actionbutton == 2) return(plot2)
      })
    
     output$plot <- renderPlot({   
        which_graph()
    
      }) 
} 

【问题讨论】:

    标签: r shiny action-button


    【解决方案1】:

    您可以创建一个 reactiveValue 并使用一个 actionButton 来切换该值。例如

    library(shiny)
    
    ui <- fluidPage(
      plotOutput("plot"),
      actionButton("button", "Click")
    )
    
    server <- function(input, output, session) {
      whichplot <- reactiveVal(TRUE)
      plot1 <- ggplot(mtcars) + aes(mpg, cyl) + geom_point()
      plot2 <- ggplot(mtcars) + aes(hp, disp) + geom_point()
      
      observeEvent(input$button, {
        whichplot(!whichplot())
      })
      
      which_graph <- reactive({
        if (whichplot()) {
          plot1
        } else {
          plot2
        }
      })
      
      output$plot <- renderPlot({   
        which_graph()
      }) 
    }
    
    shinyApp(ui, server)
    

    这里whichplot 以 TRUE 开始,然后每次按下 actionButton 时,它会在 TRUE/FALSE 之间切换。这样你就不会改变 actionButton 的值;你只是在每次按下它时更新状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多