Caching Plots in R/Shiny

caching plots in R/Shiny

Assuming you are using ggplot (which with Shiny, I would bet is a fair assumption).

  1. Create an empty list to store your grob, say Plist.
  2. When a user request a graph, create a string hash based on the shiny inputs
  3. Check if the graph is already saved, eg hash %in% names(Plist)
  4. If yes, serve up that graph
  5. If no, generate the graph, save the grob to the list, name the element by the hash, eg, Plist[hash] <- new_graph

Is there any way to pre-cache output in Shiny?

How about using a persistent cache, running the app once, where you manually change all inputs as needed (I also included an automated version, which I am not totally happy with, b/c race conditions could occur) and then in subsequent runs you have all the values properly cached?

library(shiny)
library(magrittr)
## change path to a non temp diretcory to keep that even after reboot
shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()),
"myapp-cache")))

xl <- 1:3
yl <- 1:3

ui <- fluidPage(
sliderInput("x", "x", min(xl), max(xl), min(xl), 1),
sliderInput("y", "y", min(yl), max(yl), min(yl), 1),
verbatimTextOutput("z"),
actionButton("fill", "Fill Cache")
)

server <- function(input, output, session) {
idx <- idy <- 1
r <- reactive({
message("Doing expensive computation...")
Sys.sleep(2) ## simulate expensive op
input$x + input$y
}) %>% bindCache(input$x, input$y)

observe({
req(input$fill)
if (idx != length(xl) + 1 || idy != length(yl)) {
## need the invalidateLater approach
## to allow shiny reacting on the change
## not sure whether we cannot trip over race conditions
## recommendation: do it once by hand (it's persistent anyways ;)
invalidateLater(500, session)
if (idx == length(xl) + 1) {
message("Updating y:", idy)
idx <<- 1
idy <<- idy + 1
updateSliderInput(session, "y", value = yl[[idy]])
} else {
message("Updating x:", idx)
updateSliderInput(session, "x", value = xl[[idx]])
idx <<- idx + 1
}
}
})

output$z <- renderText(r())
}

## Start app and set all values
shinyApp(ui, server)

## Close app and restart
## Cache is now filled
shinyApp(ui, server)


Related Topics



Leave a reply



Submit