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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With