Skip to content

Instantly share code, notes, and snippets.

@andodet
Created March 2, 2020 15:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andodet/fe390ae45127a80e3e526e63fc3f11bf to your computer and use it in GitHub Desktop.
Save andodet/fe390ae45127a80e3e526e63fc3f11bf to your computer and use it in GitHub Desktop.
Toy examples for plot caching in Shiny
library(shiny)
library(dplyr)
library(ggplot2)
library(R6)
library(redux)
ui <- fluidPage(titlePanel("Plot Caching Test"),
sidebarLayout(sidebarPanel(
selectInput("number", choices = seq(80000, 100000, by = 10000),
label = "Number of points", selected = 5000)
),
mainPanel(plotOutput("point_plot"))))
server <- function(input, output) {
data <- reactive({
data.frame(x = rnorm(input$number),
y = rnorm(input$number))
})
output$point_plot <- renderCachedPlot({
ggplot(data(), aes(x, y)) +
geom_point(alpha = 0.8) +
labs(title = "Random scatterplot")
},
cacheKeyExpr = { list(input$number) }
)
# Set up redis cache object
RedisCache <- R6Class(
"RedisCache",
public = list(
initialize = function(..., namespace = NULL) {
private$r <- redux::hiredis(host = '127.0.0.1', port = 6379)
# Configure 20mb cache
private$r$CONFIG_SET("maxmemory", "20mb")
private$r$CONFIG_SET("maxmemory-policy", "allkeys-lru")
private$namespace <- namespace
},
get = function(key) {
key <- paste0(private$namespace, "-", key)
s_value <- private$r$GET(key)
if (is.null(s_value)) {
return(key_missing())
}
unserialize(s_value)
},
set = function(key, value) {
key <- paste0(private$namespace, "-", key)
s_value <- serialize(value, NULL)
private$r$SET(key, s_value)
}
),
private = list(r = NULL,
namespace = NULL)
)
shinyOptions(cache = RedisCache$new(namespace = "example_app"))
}
shinyApp(ui, server)
library(shiny)
library(dplyr)
library(ggplot2)
ui <- fluidPage(titlePanel("Plot Caching Test"),
sidebarLayout(sidebarPanel(
selectInput("number", choices = seq(80000, 100000, by = 10000),
label = "Number of points", selected = 5000)
),
mainPanel(plotOutput("point_plot"))))
server <- function(input, output) {
data <- reactive({
data.frame(x = rnorm(input$number),
y = rnorm(input$number))
})
output$point_plot <- renderPlot({
ggplot(data(), aes(x, y)) +
geom_point(alpha = 0.2) +
labs(title = "Random scatterplot")
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment