Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parts to graph one by one in shiny

Tags:

r

shiny

I am trying to make some demos for my stat class. Among other things i want to show the step by step process involved. For a simplified example of what i am looking for consider the following little toy R function:

toyPlot <- function() {
  x <- 1:100/100
  y <- x+rnorm(100,0,0.2)
  plot(x,y)
  Sys.sleep(2)
  abline(lm(y~x))
  Sys.sleep(2) 
  title(main="Fitted Line Plot")
}

It draws a scatterplot, waits two second, adds the LSR line, waits two seconds and then adds the title.

Now when i do the same in shiny it waits the full 4 seconds and then does the graph in full at once.

I have spent some time looking around for a solution and found a number of commands that looked useful (session$onFlushed, invalidateLater, reactiveTimer) but i can't get any of them to do what i want.

like image 711
Wolfgang Rolke Avatar asked Nov 21 '14 19:11

Wolfgang Rolke


2 Answers

Why not bind the plot output to the value of an animation slider? You can control the duration of each stage with animationOptions.

ui <- fixedPage(
    plotOutput('myplot'),
    sliderInput('myslider', 'Steps', min=1, max=3, value=1, animate=animationOptions())
)


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

    x <- 1:100/100
    y <- x + rnorm(100, 0, 0.2)

    pfs <- list(
        function() plot(x, y) ,
        function() abline(lm(y~x)),
        function() title(main='Fitted line plot')
    )

    output$myplot <- renderPlot({
        for (i in 1:input$myslider) pfs[[i]]()
    })

}

runApp(list(ui=ui, server=server))
like image 164
Matthew Plourde Avatar answered Nov 11 '22 03:11

Matthew Plourde


Here is a way to do it assuming that turning elements on and off is acceptable. In your ui.r you should add a control (for now a chekcboxInput will do) that toggles the elements on and off. The code would be

 checkboxInput(inputId="lineCheck", label = "Show line?", value =FALSE),

 checkboxInput(inputId="titleCheck", label = "Show title?", value =FALSE),

The your plot output would be:

toyPlot <- renderPlot({
  x <- 1:100/100
  y <- x+rnorm(100,0,0.2)
  plot(x,y)
  if(input$lineCheck){ abline(lm(y~x))}
  if(input$titleCheck){ title(main="Fitted Line Plot")}
}

You can add sliders for ranges for the axes, dropdowns for color choices, symbols etc etc.

like image 39
John Paul Avatar answered Nov 11 '22 04:11

John Paul