在闪亮的应用程序中添加移动的vline(基于用户输入)

时间:2018-03-24 15:02:29

标签: r shiny

我有以下闪亮的应用程序:

library(shinydashboard)
library(ggplot2)
library(dplyr)

UI <- dashboardPage(
  dashboardHeader(title = ""),
  dashboardSidebar(
  ),
  dashboardBody(
    mainPanel(
        actionButton("goButton", "Go!"),
        plotOutput("plot_timeseries")
    )
  )
)

Server <- function(input, output) {


  output$plot_timeseries <- renderPlot({
    ggplot(mtcars, aes(mpg, disp)) + geom_point()+
      scale_x_continuous(limits = c(0,35)) +
      geom_vline(xintercept =  1)

  })

}

shinyApp(ui = UI, server = Server)

你会看到我现在在x = 1时有一个vline。但是我想要实现的是当我按下“go”按钮时应该启动一个计数器(每秒加1)。因此,按下go按钮后5秒,变量应为6,vline值应为6。

关于如何在上面的例子中使用它的任何想法?

1 个答案:

答案 0 :(得分:2)

这是一个可能的解决方案,它使用两个reactiveVal;一个用于跟踪计数器是否应该递增,另一个用于计数器的当前值。

希望这有帮助!

enter image description here

library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)

UI <- dashboardPage(
  dashboardHeader(title = ""),
  dashboardSidebar(
  ),
  dashboardBody(
    mainPanel(
      actionButton("goButton", "Go!"),
      plotOutput("plot_timeseries")
    )
  )
)

Server <- function(input, output, session) {

  counter <- reactiveVal(1)
  action <- reactiveVal(FALSE)

  # When goButton is clicked, set action() from FALSE to TRUE or the other way around.
  observeEvent(input$goButton,
               {
                 action(!action())
               })

  # Add an oberserver that invalidates every second, and increments the counter if action()==TRUE
  observe({ invalidateLater(1000, session)
    isolate({
      if(action())
      {
        # Add 1 to our counter
        counter(counter() + 1) 
      }
    })
  })

  output$plot_timeseries <- renderPlot({
    ggplot(mtcars, aes(mpg, disp)) + geom_point()+
      scale_x_continuous(limits = c(0,35)) +
      geom_vline(xintercept =  counter())
  })

}

shinyApp(ui = UI, server = Server)