在R Shiny中,计数器每秒递增并更新一个图

时间:2016-06-13 08:12:34

标签: r shiny

我试图在Shiny应用中创建一个定时计数器。当它每秒递增时,它应刷新一个具有一些取决于计数器的新特性的图。这是一个基于“老忠实”的例子。应用程序。它不起作用,但它得到了这个想法。我试图让reactiveTimer()刷新情节,并用reactiveValues()记录一个计数器。

server.R

library(shiny)

shinyServer(function(input, output) {

  refreshPlot <- reactiveTimer(intervalMs = 1000)
  vals <- reactiveValues(counter = 0)

  output$distPlot <- renderPlot({

    refreshPlot()
    vals$counter <- isolate(vals$counter) + 1

    # generate bins based on input$bins from ui.R
    x    <- faithful[, 2]
    n_bins <- input$bins + vals$counter
    bins <- seq(min(x), max(x), length.out = n_bins)

    # draw the histogram with the specified number of bins
    hist(x, breaks = bins, col = 'darkgray', border = 'white')

  })

})

ui.R

library(shiny)

shinyUI(fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )

1 个答案:

答案 0 :(得分:3)

我正在寻找

invalidateLater。谢谢,迪特。以下是可以使用的server.R。

library(shiny)

shinyServer(function(input, output, session) {

  vals <- reactiveValues(counter = 0)

  output$distPlot <- renderPlot({

    invalidateLater(millis = 1000, session)
    vals$counter <- isolate(vals$counter) + 1

    # generate bins based on input$bins from ui.R
    x    <- faithful[, 2]
    n_bins <- input$bins + vals$counter
    bins <- seq(min(x), max(x), length.out = n_bins)

    # draw the histogram with the specified number of bins
    hist(x, breaks = bins, col = 'darkgray', border = 'white')

  })

})
相关问题