caching plots in R/Shiny
Assuming you are using ggplot
(which with Shiny, I would bet is a fair assumption).
- Create an empty list to store your grob, say
Plist
. - When a user request a graph, create a string hash based on the shiny inputs
- Check if the graph is already saved, eg
hash %in% names(Plist)
- If yes, serve up that graph
- 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
Extract English Words from a Text in R
Assign Color to 2 Different Geoms and Get 2 Different Legends
Why Does Withcallinghandlers Still Stops Execution
Plot a Function with Several Arguments in R
Removing Everything After First 'Backslash' in a String
Follow-Up: Generalizing a Data.Frame Subsetting Function 2
R - Calculate Test Mse Given a Trained Model from a Training Set and a Test Set
Error: Could Not Find Build Tools Necessary to Build Dplyr
Splitting Text to Words with R and Csplit()
How to Do a Glm When "Contrasts Can Be Applied Only to Factors with 2 or More Levels"
Reshape R Data with User Entries in Rows, Collapsing for Each User
Add a Constant Value to All Rows in a Dataframe
Generating a Date from a String with a 'Month-Year' Format
Take the Subsets of a Data.Frame with the Same Feature and Select a Single Row from Each Subset
How to Automate Nested Sections in Rmds Which Include Text, Maps and Tables