Toy examples for plot caching in Shiny
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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