Simulate real time data visualization using Shiny

Viewed 942

I am creating a POC, where real time update will reflect on my shiny application. The idea is to plot the frequency distribution of the data that is being generated from a server. Since I do not have access to the server yet, I have simulated a data creation which I am feeding to my plot. I can see the data properly on my console, but nothing is being displayed on my application. I am sure that there is something I am missing out. I think the reason I am unable to view the plot is because the data is getting updated faster than the rendering speed. Is there any way to modify that.

library(shiny)
library(magrittr)
library(plotly)


ui <- shinyServer(fluidPage(
  plotOutput("plot")
))


alarms = c("NodeDown","GrowthRate","DecayRate","DiskFull","ServiceDown","Planned_shutdown","etc.....etc","ServerOutage",
           "No Casue")

server <- shinyServer(function(input, output, session){
  # Function to get new observations
  get_new_data <- function(){

    new = sample(alarms,1)
#    data <- new %>% rbind %>% data.frame
    return(new)
  }

  # Initialize my_data
  my_data <<- get_new_data()

  # Function to update my_data
  update_data <- function(){
    my_data <<- c(get_new_data(), my_data)

  }

  output$plot <- renderPlotly({

    invalidateLater(1000, session)
    update_data()
#    print(my_data)
    dd = update_data()
    dd = as.data.frame(table(dd))
    print(dd)
    plot_ly(dd, x = ~dd, y = ~Freq)
  })

  # Plot the 30 most recent values
#  output$first_column <- renderPlot({
#    print("Render")
#    invalidateLater(1000, session)
#    update_data()
#    print(my_data)
#    plot(X1 ~ 1, data=my_data[1:30,], ylim=c(-3, 3), las=1, type="l")
#  })
})

shinyApp(ui=ui,server=server)
1 Answers

You should use reactiveValues to append your vector, and use reactiveTimer with observeEvent to trigger it every second

Also, if you want to use renderPlotly in server, you should use plotlyOutput rather than plotOutput in ui

Try this:

library(shiny)
library(magrittr)
library(plotly)


ui <- shinyServer(fluidPage(
  plotlyOutput("plot")
))


alarms = c("NodeDown","GrowthRate","DecayRate","DiskFull","ServiceDown","Planned_shutdown","etc.....etc","ServerOutage",
           "No Casue")

server <- shinyServer(function(input, output, session){
  get_new_data <- function(){
    new = sample(alarms,1)
    return(new)
  }

  my_data <-reactiveValues(data=get_new_data())

  observeEvent(reactiveTimer(2000)(),{ # Trigger every 2 seconds
    my_data$data<-c(get_new_data(),my_data$data)
    print(my_data$data)
  })

  output$plot <- renderPlotly({
    dd=as.data.frame(table(my_data$data))
    print(dd)
    plot_ly(dd, x = ~Var1, y = ~Freq)
  })

})

shinyApp(ui=ui,server=server)
Related