Debian Codegraph @

man/renderCachedPlot.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/render-cached-plot.R
3 \name{renderCachedPlot}
4 \alias{renderCachedPlot}
5 \title{Plot output with cached images}
6 \usage{
7 renderCachedPlot(
8 expr,
9 cacheKeyExpr,
10 sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2),
11 res = 72,
12 cache = "app",
13 ...,
14 alt = "Plot object",
15 outputArgs = list(),
16 width = NULL,
17 height = NULL
18 )
19 }
20 \arguments{
21 \item{expr}{An expression that generates a plot.}
22
23 \item{cacheKeyExpr}{An expression that returns a cache key. This key should
24 be a unique identifier for a plot: the assumption is that if the cache key
25 is the same, then the plot will be the same.}
26
27 \item{sizePolicy}{A function that takes two arguments, \code{width} and
28 \code{height}, and returns a list with \code{width} and \code{height}. The
29 purpose is to round the actual pixel dimensions from the browser to some
30 other dimensions, so that this will not generate and cache images of every
31 possible pixel dimension. See \code{\link[=sizeGrowthRatio]{sizeGrowthRatio()}} for more
32 information on the default sizing policy.}
33
34 \item{res}{The resolution of the PNG, in pixels per inch.}
35
36 \item{cache}{The scope of the cache, or a cache object. This can be \code{"app"}
37 (the default), \code{"session"}, or a cache object like a
38 \code{\link[cachem:cache_disk]{cachem::cache_disk()}}. See the Cache Scoping section for more information.}
39
40 \item{...}{Arguments to be passed through to \code{\link[=plotPNG]{plotPNG()}}.
41 These can be used to set the width, height, background color, etc.}
42
43 \item{alt}{Alternate text for the HTML \verb{<img>} tag if it cannot be displayed
44 or viewed (i.e., the user uses a screen reader). In addition to a character
45 string, the value may be a reactive expression (or a function referencing
46 reactive values) that returns a character string. If the value is \code{NA} (the
47 default), then \code{ggplot2::get_alt_text()} is used to extract alt text from
48 ggplot objects; for other plots, \code{NA} results in alt text of "Plot object".
49 \code{NULL} or \code{""} is not recommended because those should be limited to
50 decorative images.}
51
52 \item{outputArgs}{A list of arguments to be passed through to the implicit
53 call to \code{\link[=plotOutput]{plotOutput()}} when \code{renderPlot} is used in an
54 interactive R Markdown document.}
55
56 \item{width, height}{not used. They are specified via the argument
57 \code{sizePolicy}.}
58 }
59 \description{
60 Renders a reactive plot, with plot images cached to disk. As of Shiny 1.6.0,
61 this is a shortcut for using \code{\link[=bindCache]{bindCache()}} with \code{\link[=renderPlot]{renderPlot()}}.
62 }
63 \details{
64 \code{expr} is an expression that generates a plot, similar to that in
65 \code{renderPlot}. Unlike with \code{renderPlot}, this expression does not
66 take reactive dependencies. It is re-executed only when the cache key
67 changes.
68
69 \code{cacheKeyExpr} is an expression which, when evaluated, returns an object
70 which will be serialized and hashed using the \code{\link[rlang:hash]{rlang::hash()}}
71 function to generate a string that will be used as a cache key. This key is
72 used to identify the contents of the plot: if the cache key is the same as a
73 previous time, it assumes that the plot is the same and can be retrieved from
74 the cache.
75
76 This \code{cacheKeyExpr} is reactive, and so it will be re-evaluated when any
77 upstream reactives are invalidated. This will also trigger re-execution of
78 the plotting expression, \code{expr}.
79
80 The key should consist of "normal" R objects, like vectors and lists. Lists
81 should in turn contain other normal R objects. If the key contains
82 environments, external pointers, or reference objects --- or even if it has
83 such objects attached as attributes --- then it is possible that it will
84 change unpredictably even when you do not expect it to. Additionally, because
85 the entire key is serialized and hashed, if it contains a very large object
86 --- a large data set, for example --- there may be a noticeable performance
87 penalty.
88
89 If you face these issues with the cache key, you can work around them by
90 extracting out the important parts of the objects, and/or by converting them
91 to normal R objects before returning them. Your expression could even
92 serialize and hash that information in an efficient way and return a string,
93 which will in turn be hashed (very quickly) by the
94 \code{\link[rlang:hash]{rlang::hash()}} function.
95
96 Internally, the result from \code{cacheKeyExpr} is combined with the name of
97 the output (if you assign it to \code{output$plot1}, it will be combined
98 with \code{"plot1"}) to form the actual key that is used. As a result, even
99 if there are multiple plots that have the same \code{cacheKeyExpr}, they
100 will not have cache key collisions.
101 }
102 \section{Interactive plots}{
103
104
105 \code{renderCachedPlot} can be used to create interactive plots. See
106 \code{\link[=plotOutput]{plotOutput()}} for more information and examples.
107 }
108
109 \examples{
110 ## Only run examples in interactive R sessions
111 if (interactive()) {
112
113 # A basic example that uses the default app-scoped memory cache.
114 # The cache will be shared among all simultaneous users of the application.
115 shinyApp(
116 fluidPage(
117 sidebarLayout(
118 sidebarPanel(
119 sliderInput("n", "Number of points", 4, 32, value = 8, step = 4)
120 ),
121 mainPanel(plotOutput("plot"))
122 )
123 ),
124 function(input, output, session) {
125 output$plot <- renderCachedPlot({
126 Sys.sleep(2) # Add an artificial delay
127 seqn <- seq_len(input$n)
128 plot(mtcars$wt[seqn], mtcars$mpg[seqn],
129 xlim = range(mtcars$wt), ylim = range(mtcars$mpg))
130 },
131 cacheKeyExpr = { list(input$n) }
132 )
133 }
134 )
135
136
137
138 # An example uses a data object shared across sessions. mydata() is part of
139 # the cache key, so when its value changes, plots that were previously
140 # stored in the cache will no longer be used (unless mydata() changes back
141 # to its previous value).
142 mydata <- reactiveVal(data.frame(x = rnorm(400), y = rnorm(400)))
143
144 ui <- fluidPage(
145 sidebarLayout(
146 sidebarPanel(
147 sliderInput("n", "Number of points", 50, 400, 100, step = 50),
148 actionButton("newdata", "New data")
149 ),
150 mainPanel(
151 plotOutput("plot")
152 )
153 )
154 )
155
156 server <- function(input, output, session) {
157 observeEvent(input$newdata, {
158 mydata(data.frame(x = rnorm(400), y = rnorm(400)))
159 })
160
161 output$plot <- renderCachedPlot(
162 {
163 Sys.sleep(2)
164 d <- mydata()
165 seqn <- seq_len(input$n)
166 plot(d$x[seqn], d$y[seqn], xlim = range(d$x), ylim = range(d$y))
167 },
168 cacheKeyExpr = { list(input$n, mydata()) },
169 )
170 }
171
172 shinyApp(ui, server)
173
174
175 # A basic application with two plots, where each plot in each session has
176 # a separate cache.
177 shinyApp(
178 fluidPage(
179 sidebarLayout(
180 sidebarPanel(
181 sliderInput("n", "Number of points", 4, 32, value = 8, step = 4)
182 ),
183 mainPanel(
184 plotOutput("plot1"),
185 plotOutput("plot2")
186 )
187 )
188 ),
189 function(input, output, session) {
190 output$plot1 <- renderCachedPlot({
191 Sys.sleep(2) # Add an artificial delay
192 seqn <- seq_len(input$n)
193 plot(mtcars$wt[seqn], mtcars$mpg[seqn],
194 xlim = range(mtcars$wt), ylim = range(mtcars$mpg))
195 },
196 cacheKeyExpr = { list(input$n) },
197 cache = cachem::cache_mem()
198 )
199 output$plot2 <- renderCachedPlot({
200 Sys.sleep(2) # Add an artificial delay
201 seqn <- seq_len(input$n)
202 plot(mtcars$wt[seqn], mtcars$mpg[seqn],
203 xlim = range(mtcars$wt), ylim = range(mtcars$mpg))
204 },
205 cacheKeyExpr = { list(input$n) },
206 cache = cachem::cache_mem()
207 )
208 }
209 )
210
211 }
212
213 \dontrun{
214 # At the top of app.R, this set the application-scoped cache to be a memory
215 # cache that is 20 MB in size, and where cached objects expire after one
216 # hour.
217 shinyOptions(cache = cachem::cache_mem(max_size = 20e6, max_age = 3600))
218
219 # At the top of app.R, this set the application-scoped cache to be a disk
220 # cache that can be shared among multiple concurrent R processes, and is
221 # deleted when the system reboots.
222 shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()), "myapp-cache")))
223
224 # At the top of app.R, this set the application-scoped cache to be a disk
225 # cache that can be shared among multiple concurrent R processes, and
226 # persists on disk across reboots.
227 shinyOptions(cache = cachem::cache_disk("./myapp-cache"))
228
229 # At the top of the server function, this set the session-scoped cache to be
230 # a memory cache that is 5 MB in size.
231 server <- function(input, output, session) {
232 shinyOptions(cache = cachem::cache_mem(max_size = 5e6))
233
234 output$plot <- renderCachedPlot(
235 ...,
236 cache = "session"
237 )
238 }
239
240 }
241 }
242 \seealso{
243 See \code{\link[=renderPlot]{renderPlot()}} for the regular, non-cached version of this
244 function. It can be used with \code{\link[=bindCache]{bindCache()}} to get the same effect as
245 \code{renderCachedPlot()}. For more about configuring caches, see
246 \code{\link[cachem:cache_mem]{cachem::cache_mem()}} and \code{\link[cachem:cache_disk]{cachem::cache_disk()}}.
247 }