File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
inst/examples/shiny/stream Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ library(shiny )
2+ library(plotly )
3+
4+ ui <- fluidPage(
5+ actionButton(" stream" , " Turn stream on/off" ),
6+ plotlyOutput(" plot" )
7+ )
8+
9+ server <- function (input , output , session ) {
10+
11+ # initial values
12+ yint <- c(0 , 1 )
13+
14+ # initiate graph with initial values
15+ output $ plot <- renderPlotly({
16+ plot_ly(y = yint , x = seq_along(yint )) %> %
17+ add_lines()
18+ })
19+
20+ # reactiveValues() act very much like input values, but may be used to
21+ # maintain state (e.g., are we currently streaming?)
22+ rv <- reactiveValues(
23+ stream = FALSE ,
24+ yend = sum(yint ),
25+ n = length(yint )
26+ )
27+
28+ # turn streaming on/off when the button is pressed
29+ observeEvent(input $ stream , {
30+ rv $ stream <- if (rv $ stream ) FALSE else TRUE
31+ })
32+
33+ observe({
34+ # if we're not streaming, don't do anything
35+ if (! rv $ stream ) return ()
36+
37+ # re-execute this code block to every 100 milliseconds
38+ invalidateLater(100 , session )
39+ # changing a reactive value "invalidates" it, so isolate() is needed
40+ # to avoid recursion
41+ isolate({
42+ rv $ n <- rv $ n + 1
43+ rv $ yend <- rv $ yend + sample(c(- 1 , 1 ), 1 )
44+ })
45+
46+ # add the new value to the plot
47+ plotlyProxy(" plot" , session ) %> %
48+ plotlyProxyInvoke(
49+ " extendTraces" ,
50+ list (
51+ y = list (list (rv $ yend )),
52+ x = list (list (rv $ n ))
53+ ),
54+ list (0 )
55+ )
56+ })
57+
58+ }
59+
60+ shinyApp(ui , server )
You can’t perform that action at this time.
0 commit comments