Debian Codegraph @

R/render-plot.R

raw
1 #' Plot Output
2 #'
3 #' Renders a reactive plot that is suitable for assigning to an `output`
4 #' slot.
5 #'
6 #' The corresponding HTML output tag should be `div` or `img` and have
7 #' the CSS class name `shiny-plot-output`.
8 #'
9 #' @section Interactive plots:
10 #'
11 #' With ggplot2 graphics, the code in `renderPlot` should return a ggplot
12 #' object; if instead the code prints the ggplot2 object with something like
13 #' `print(p)`, then the coordinates for interactive graphics will not be
14 #' properly scaled to the data space.
15 #'
16 #' See [plotOutput()] for more information about interactive plots.
17 #'
18 #' @seealso For the corresponding client-side output function, and example
19 #' usage, see [plotOutput()]. For more details on how the plots are
20 #' generated, and how to control the output, see [plotPNG()].
21 #' [renderCachedPlot()] offers a way to cache generated plots to
22 #' expedite the rendering of identical plots.
23 #'
24 #' @param expr An expression that generates a plot.
25 #' @param width,height Height and width can be specified in three ways:
26 #' * `"auto"`, the default, uses the size specified by [plotOutput()]
27 #' (i.e. the `offsetWidth`/`offsetHeight`` of the HTML element bound to
28 #' this plot.)
29 #' * An integer, defining the width/height in pixels.
30 #' * A function that returns the width/height in pixels (or `"auto"`).
31 #' The function is executed in a reactive context so that you can refer to
32 #' reactive values and expression to make the width/height reactive.
33 #'
34 #' When rendering an inline plot, you must provide numeric values (in pixels)
35 #' to both \code{width} and \code{height}.
36 #' @param res Resolution of resulting plot, in pixels per inch. This value is
37 #' passed to [plotPNG()]. Note that this affects the resolution of PNG
38 #' rendering in R; it won't change the actual ppi of the browser.
39 #' @param alt Alternate text for the HTML `<img>` tag if it cannot be displayed
40 #' or viewed (i.e., the user uses a screen reader). In addition to a character
41 #' string, the value may be a reactive expression (or a function referencing
42 #' reactive values) that returns a character string. If the value is `NA` (the
43 #' default), then `ggplot2::get_alt_text()` is used to extract alt text from
44 #' ggplot objects; for other plots, `NA` results in alt text of "Plot object".
45 #' `NULL` or `""` is not recommended because those should be limited to
46 #' decorative images.
47 #' @param ... Arguments to be passed through to [plotPNG()].
48 #' These can be used to set the width, height, background color, etc.
49 #' @inheritParams renderUI
50 #' @param execOnResize If `FALSE` (the default), then when a plot is
51 #' resized, Shiny will *replay* the plot drawing commands with
52 #' [grDevices::replayPlot()] instead of re-executing `expr`.
53 #' This can result in faster plot redrawing, but there may be rare cases where
54 #' it is undesirable. If you encounter problems when resizing a plot, you can
55 #' have Shiny re-execute the code on resize by setting this to `TRUE`.
56 #' @param outputArgs A list of arguments to be passed through to the implicit
57 #' call to [plotOutput()] when `renderPlot` is used in an
58 #' interactive R Markdown document.
59 #' @export
60 renderPlot <- function(expr, width = 'auto', height = 'auto', res = 72, ...,
61 alt = NA,
62 env = parent.frame(), quoted = FALSE,
63 execOnResize = FALSE, outputArgs = list()
64 ) {
65
66 func <- installExprFunction(
67 expr, "func", env, quoted,
68 label = "renderPlot",
69 # This ..stacktraceon is matched by a ..stacktraceoff.. when plotFunc
70 # is called
71 ..stacktraceon = TRUE
72 )
73
74 args <- list(...)
75
76 if (is.reactive(width))
77 widthWrapper <- width
78 else if (is.function(width))
79 widthWrapper <- reactive({ width() })
80 else
81 widthWrapper <- function() { width }
82
83 if (is.reactive(height))
84 heightWrapper <- height
85 else if (is.function(height))
86 heightWrapper <- reactive({ height() })
87 else
88 heightWrapper <- function() { height }
89
90 if (is.reactive(alt))
91 altWrapper <- alt
92 else if (is.function(alt))
93 altWrapper <- reactive({ alt() })
94 else
95 altWrapper <- function() { alt }
96
97 # This is the function that will be used as getDims by default, but it can be
98 # overridden (which happens when bindCache() is used).
99 getDimsDefault <- function() {
100 width <- widthWrapper()
101 height <- heightWrapper()
102
103 # Note that these are reactive calls. A change to the width and height
104 # will inherently cause a reactive plot to redraw (unless width and
105 # height were explicitly specified).
106 if (width == 'auto')
107 width <- session$clientData[[paste0('output_', outputName, '_width')]]
108 if (height == 'auto')
109 height <- session$clientData[[paste0('output_', outputName, '_height')]]
110
111 list(width = width, height = height)
112 }
113
114 # Vars to store session and output, so that they can be accessed from
115 # the plotObj() reactive.
116 session <- NULL
117 outputName <- NULL
118 getDims <- NULL
119
120 # Calls drawPlot, invoking the user-provided `func` (which may or may not
121 # return a promise). The idea is that the (cached) return value from this
122 # reactive can be used for varying width/heights, as it includes the
123 # displaylist, which is resolution independent.
124 drawReactive <- reactive(label = "plotObj", {
125 hybrid_chain(
126 {
127 # If !execOnResize, don't invalidate when width/height changes.
128 dims <- if (execOnResize) getDims() else isolate(getDims())
129 pixelratio <- session$clientData$pixelratio %||% 1
130 do.call("drawPlot", c(
131 list(
132 name = outputName,
133 session = session,
134 func = func,
135 width = dims$width,
136 height = dims$height,
137 alt = altWrapper(),
138 pixelratio = pixelratio,
139 res = res
140 ), args))
141 },
142 catch = function(reason) {
143 # Non-isolating read. A common reason for errors in plotting is because
144 # the dimensions are too small. By taking a dependency on width/height,
145 # we can try again if the plot output element changes size.
146 getDims()
147
148 # Propagate the error
149 stop(reason)
150 }
151 )
152 })
153
154 # This function is the one that's returned from renderPlot(), and gets
155 # wrapped in an observer when the output value is assigned.
156 # The `get_dims` parameter defaults to `getDimsDefault`. However, it can be
157 # overridden, so that `bindCache` can use a different version.
158 renderFunc <- function(shinysession, name, ..., get_dims = getDimsDefault) {
159
160 outputName <<- name
161 session <<- shinysession
162 if (is.null(getDims)) getDims <<- get_dims
163
164 hybrid_chain(
165 drawReactive(),
166 function(result) {
167 dims <- getDims()
168 pixelratio <- session$clientData$pixelratio %||% 1
169 result <- do.call("resizeSavedPlot", c(
170 list(name, shinysession, result, dims$width, dims$height, altWrapper(), pixelratio, res),
171 args
172 ))
173
174 result$img
175 }
176 )
177 }
178
179 # If renderPlot isn't going to adapt to the height of the div, then the
180 # div needs to adapt to the height of renderPlot. By default, plotOutput
181 # sets the height to 400px, so to make it adapt we need to override it
182 # with NULL.
183 outputFunc <- plotOutput
184 if (!identical(height, 'auto')) formals(outputFunc)['height'] <- list(NULL)
185
186 markedFunc <- markRenderFunction(
187 outputFunc,
188 renderFunc,
189 outputArgs,
190 cacheHint = list(userExpr = installedFuncExpr(func), res = res)
191 )
192 class(markedFunc) <- c("shiny.renderPlot", class(markedFunc))
193 markedFunc
194 }
195
196 resizeSavedPlot <- function(name, session, result, width, height, alt, pixelratio, res, ...) {
197 if (isTRUE(result$img$width == width && result$img$height == height &&
198 result$pixelratio == pixelratio && result$res == res)) {
199 return(result)
200 }
201
202 if (isNamespaceLoaded("showtext")) {
203 showtextOpts <- showtext::showtext_opts(dpi = res*pixelratio)
204 on.exit({showtext::showtext_opts(showtextOpts)}, add = TRUE)
205 }
206
207 coordmap <- NULL
208 outfile <- plotPNG(function() {
209 grDevices::replayPlot(result$recordedPlot)
210 coordmap <<- getCoordmap(result$plotResult, width*pixelratio, height*pixelratio, res*pixelratio)
211 }, width = width*pixelratio, height = height*pixelratio, res = res*pixelratio, ...)
212 on.exit(unlink(outfile), add = TRUE)
213
214 result$img <- list(
215 src = session$fileUrl(name, outfile, contentType = "image/png"),
216 width = width,
217 height = height,
218 alt = result$alt,
219 coordmap = coordmap,
220 error = attr(coordmap, "error", exact = TRUE)
221 )
222
223 result
224 }
225
226 drawPlot <- function(name, session, func, width, height, alt, pixelratio, res, ...) {
227 # 1. Start PNG
228 # 2. Enable displaylist recording
229 # 3. Call user-defined func
230 # 4. Print/save result, if visible
231 # 5. Snapshot displaylist
232 # 6. Form coordmap
233 # 7. End PNG (in finally)
234 # 8. Form img tag
235 # 9. Return img, value, displaylist, coordmap
236 # 10. On error, take width and height dependency
237
238 outfile <- tempfile(fileext='.png') # If startPNG throws, this could leak. Shrug.
239 device <- startPNG(outfile, width*pixelratio, height*pixelratio, res = res*pixelratio, ...)
240 domain <- createGraphicsDevicePromiseDomain(device)
241 grDevices::dev.control(displaylist = "enable")
242
243 # In some cases (at least when `png(type='cairo')), showtext's font
244 # rendering needs to know about the device's resolution to work properly.
245 # I don't see any immediate harm in setting the dpi option for any device,
246 # but it's worth noting that the option doesn't currently work with CairoPNG.
247 # https://github.com/yixuan/showtext/issues/33
248 showtextOpts <- if (isNamespaceLoaded("showtext")) {
249 showtext::showtext_opts(dpi = res*pixelratio)
250 } else {
251 NULL
252 }
253
254 hybrid_chain(
255 hybrid_chain(
256 with_promise_domain(domain, {
257 hybrid_chain(
258 func(),
259 function(value) {
260 res <- withVisible(value)
261 if (res$visible) {
262 # A modified version of print.ggplot which returns the built ggplot object
263 # as well as the gtable grob. This overrides the ggplot::print.ggplot
264 # method, but only within the context of renderPlot. The reason this needs
265 # to be a (pseudo) S3 method is so that, if an object has a class in
266 # addition to ggplot, and there's a print method for that class, that we
267 # won't override that method. https://github.com/rstudio/shiny/issues/841
268 print.ggplot <- custom_print.ggplot
269 # For compatibility with ggplot2 >v4.0.0
270 `print.ggplot2::ggplot` <- custom_print.ggplot
271
272 # Use capture.output to squelch printing to the actual console; we
273 # are only interested in plot output
274 utils::capture.output({
275 # This ..stacktraceon.. negates the ..stacktraceoff.. that wraps
276 # the call to plotFunc. The value needs to be printed just in case
277 # it's an object that requires printing to generate plot output,
278 # similar to ggplot2. But for base graphics, it would already have
279 # been rendered when func was called above, and the print should
280 # have no effect.
281 result <- ..stacktraceon..(print(res$value))
282 # TODO jcheng 2017-04-11: Verify above ..stacktraceon..
283 })
284 result
285 } else {
286 # Not necessary, but I wanted to make it explicit
287 NULL
288 }
289 },
290 function(value) {
291 list(
292 plotResult = value,
293 recordedPlot = grDevices::recordPlot(),
294 coordmap = getCoordmap(value, width*pixelratio, height*pixelratio, res*pixelratio),
295 pixelratio = pixelratio,
296 alt = if (anyNA(alt)) getAltText(value) else alt,
297 res = res
298 )
299 }
300 )
301 }),
302 finally = function() {
303 grDevices::dev.off(device)
304 if (length(showtextOpts)) {
305 showtext::showtext_opts(showtextOpts)
306 }
307 }
308 ),
309 function(result) {
310 result$img <- dropNulls(list(
311 src = session$fileUrl(name, outfile, contentType = 'image/png'),
312 width = width,
313 height = height,
314 alt = result$alt,
315 coordmap = result$coordmap,
316 # Get coordmap error message if present
317 error = attr(result$coordmap, "error", exact = TRUE)
318 ))
319
320 result
321 },
322 finally = function() {
323 unlink(outfile)
324 }
325 )
326 }
327
328 # A modified version of print.ggplot which returns the built ggplot object
329 # as well as the gtable grob. This overrides the ggplot::print.ggplot
330 # method, but only within the context of renderPlot. The reason this needs
331 # to be a (pseudo) S3 method is so that, if an object has a class in
332 # addition to ggplot, and there's a print method for that class, that we
333 # won't override that method. https://github.com/rstudio/shiny/issues/841
334 custom_print.ggplot <- function(x) {
335 grid::grid.newpage()
336
337 build <- ggplot2::ggplot_build(x)
338
339 gtable <- ggplot2::ggplot_gtable(build)
340 grid::grid.draw(gtable)
341
342 structure(list(
343 build = build,
344 gtable = gtable
345 ), class = "ggplot_build_gtable")
346 }
347
348 # Infer alt text description from renderPlot() value
349 # (currently just ggplot2 is supported)
350 getAltText <- function(x, default = "Plot object") {
351 # Since, inside renderPlot(), custom_print.ggplot()
352 # overrides print.ggplot, this class indicates a ggplot()
353 if (!inherits(x, "ggplot_build_gtable")) {
354 return(default)
355 }
356 # ggplot2::get_alt_text() was added in v3.3.4
357 # https://github.com/tidyverse/ggplot2/pull/4482
358 get_alt <- getNamespace("ggplot2")$get_alt_text
359 if (!is.function(get_alt)) {
360 return(default)
361 }
362 alt <- paste(get_alt(x$build), collapse = " ")
363 if (nzchar(alt)) alt else default
364 }
365
366 # The coordmap extraction functions below return something like the examples
367 # below. For base graphics:
368 # plot(mtcars$wt, mtcars$mpg)
369 # str(getPrevPlotCoordmap(400, 300))
370 # List of 2
371 # $ panels:List of 1
372 # ..$ :List of 4
373 # .. ..$ domain :List of 4
374 # .. .. ..$ left : num 1.36
375 # .. .. ..$ right : num 5.58
376 # .. .. ..$ bottom: num 9.46
377 # .. .. ..$ top : num 34.8
378 # .. ..$ range :List of 4
379 # .. .. ..$ left : num 65.6
380 # .. .. ..$ right : num 366
381 # .. .. ..$ bottom: num 238
382 # .. .. ..$ top : num 48.2
383 # .. ..$ log :List of 2
384 # .. .. ..$ x: NULL
385 # .. .. ..$ y: NULL
386 # .. ..$ mapping: Named list()
387 # $ dims :List of 2
388 # ..$ width : num 400
389 # ..$ height: num 300
390 #
391 # For ggplot2, first you need to define the print.ggplot function from inside
392 # renderPlot, then use it to print the plot:
393 # print.ggplot <- function(x) {
394 # grid::grid.newpage()
395 #
396 # build <- ggplot2::ggplot_build(x)
397 #
398 # gtable <- ggplot2::ggplot_gtable(build)
399 # grid::grid.draw(gtable)
400 #
401 # structure(list(
402 # build = build,
403 # gtable = gtable
404 # ), class = "ggplot_build_gtable")
405 # }
406 #
407 # p <- print(ggplot(mtcars, aes(wt, mpg)) + geom_point())
408 # str(getGgplotCoordmap(p, 400, 300, 72))
409 # List of 2
410 # $ panels:List of 1
411 # ..$ :List of 8
412 # .. ..$ panel : num 1
413 # .. ..$ row : num 1
414 # .. ..$ col : num 1
415 # .. ..$ panel_vars: Named list()
416 # .. ..$ log :List of 2
417 # .. .. ..$ x: NULL
418 # .. .. ..$ y: NULL
419 # .. ..$ domain :List of 4
420 # .. .. ..$ left : num 1.32
421 # .. .. ..$ right : num 5.62
422 # .. .. ..$ bottom: num 9.22
423 # .. .. ..$ top : num 35.1
424 # .. ..$ mapping :List of 2
425 # .. .. ..$ x: chr "wt"
426 # .. .. ..$ y: chr "mpg"
427 # .. ..$ range :List of 4
428 # .. .. ..$ left : num 33.3
429 # .. .. ..$ right : num 355
430 # .. .. ..$ bottom: num 328
431 # .. .. ..$ top : num 5.48
432 # $ dims :List of 2
433 # ..$ width : num 400
434 # ..$ height: num 300
435 #
436 # With a faceted ggplot2 plot, the outer list contains two objects, each of
437 # which represents one panel. In this example, there is one panelvar, but there
438 # can be up to two of them.
439 # p <- print(ggplot(mpg) + geom_point(aes(fl, cty), alpha = 0.2) + facet_wrap(~drv, scales = "free_x"))
440 # str(getGgplotCoordmap(p, 500, 400, 72))
441 # List of 2
442 # $ panels:List of 3
443 # ..$ :List of 8
444 # .. ..$ panel : num 1
445 # .. ..$ row : int 1
446 # .. ..$ col : int 1
447 # .. ..$ panel_vars:List of 1
448 # .. .. ..$ panelvar1: chr "4"
449 # .. ..$ log :List of 2
450 # .. .. ..$ x: NULL
451 # .. .. ..$ y: NULL
452 # .. ..$ domain :List of 5
453 # .. .. ..$ left : num 0.4
454 # .. .. ..$ right : num 4.6
455 # .. .. ..$ bottom : num 7.7
456 # .. .. ..$ top : num 36.3
457 # .. .. ..$ discrete_limits:List of 1
458 # .. .. .. ..$ x: chr [1:4] "d" "e" "p" "r"
459 # .. ..$ mapping :List of 3
460 # .. .. ..$ x : chr "fl"
461 # .. .. ..$ y : chr "cty"
462 # .. .. ..$ panelvar1: chr "drv"
463 # .. ..$ range :List of 4
464 # .. .. ..$ left : num 33.3
465 # .. .. ..$ right : num 177
466 # .. .. ..$ bottom: num 448
467 # .. .. ..$ top : num 23.1
468 # ..$ :List of 8
469 # .. ..$ panel : num 2
470 # .. ..$ row : int 1
471 # .. ..$ col : int 2
472 # .. ..$ panel_vars:List of 1
473 # .. .. ..$ panelvar1: chr "f"
474 # .. ..$ log :List of 2
475 # .. .. ..$ x: NULL
476 # .. .. ..$ y: NULL
477 # .. ..$ domain :List of 5
478 # .. .. ..$ left : num 0.4
479 # .. .. ..$ right : num 5.6
480 # .. .. ..$ bottom : num 7.7
481 # .. .. ..$ top : num 36.3
482 # .. .. ..$ discrete_limits:List of 1
483 # .. .. .. ..$ x: chr [1:5] "c" "d" "e" "p" ...
484 # .. ..$ mapping :List of 3
485 # .. .. ..$ x : chr "fl"
486 # .. .. ..$ y : chr "cty"
487 # .. .. ..$ panelvar1: chr "drv"
488 # .. ..$ range :List of 4
489 # .. .. ..$ left : num 182
490 # .. .. ..$ right : num 326
491 # .. .. ..$ bottom: num 448
492 # .. .. ..$ top : num 23.1
493 # ..$ :List of 8
494 # .. ..$ panel : num 3
495 # .. ..$ row : int 1
496 # .. ..$ col : int 3
497 # .. ..$ panel_vars:List of 1
498 # .. .. ..$ panelvar1: chr "r"
499 # .. ..$ log :List of 2
500 # .. .. ..$ x: NULL
501 # .. .. ..$ y: NULL
502 # .. ..$ domain :List of 5
503 # .. .. ..$ left : num 0.4
504 # .. .. ..$ right : num 3.6
505 # .. .. ..$ bottom : num 7.7
506 # .. .. ..$ top : num 36.3
507 # .. .. ..$ discrete_limits:List of 1
508 # .. .. .. ..$ x: chr [1:3] "e" "p" "r"
509 # .. ..$ mapping :List of 3
510 # .. .. ..$ x : chr "fl"
511 # .. .. ..$ y : chr "cty"
512 # .. .. ..$ panelvar1: chr "drv"
513 # .. ..$ range :List of 4
514 # .. .. ..$ left : num 331
515 # .. .. ..$ right : num 475
516 # .. .. ..$ bottom: num 448
517 # .. .. ..$ top : num 23.1
518 # $ dims :List of 2
519 # ..$ width : num 500
520 # ..$ height: num 400
521
522 getCoordmap <- function(x, width, height, res) {
523 if (inherits(x, "ggplot_build_gtable")) {
524 getGgplotCoordmap(x, width, height, res)
525 } else {
526 getPrevPlotCoordmap(width, height)
527 }
528 }
529
530 # Get a coordmap for the previous plot made with base graphics.
531 # Requires width and height of output image, in pixels.
532 # Must be called before the graphics device is closed.
533 getPrevPlotCoordmap <- function(width, height) {
534 usrCoords <- graphics::par('usr')
535 usrBounds <- usrCoords
536 if (graphics::par('xlog')) {
537 usrBounds[c(1,2)] <- 10 ^ usrBounds[c(1,2)]
538 }
539 if (graphics::par('ylog')) {
540 usrBounds[c(3,4)] <- 10 ^ usrBounds[c(3,4)]
541 }
542
543 # Wrapped in double list because other types of plots can have multiple panels.
544 panel_info <- list(list(
545 # Bounds of the plot area, in data space
546 domain = list(
547 left = usrCoords[1],
548 right = usrCoords[2],
549 bottom = usrCoords[3],
550 top = usrCoords[4]
551 ),
552 # The bounds of the plot area, in DOM pixels
553 range = list(
554 left = graphics::grconvertX(usrBounds[1], 'user', 'ndc') * width,
555 right = graphics::grconvertX(usrBounds[2], 'user', 'ndc') * width,
556 bottom = (1-graphics::grconvertY(usrBounds[3], 'user', 'ndc')) * height - 1,
557 top = (1-graphics::grconvertY(usrBounds[4], 'user', 'ndc')) * height - 1
558 ),
559 log = list(
560 x = if (graphics::par('xlog')) 10 else NULL,
561 y = if (graphics::par('ylog')) 10 else NULL
562 ),
563 # We can't extract the original variable names from a base graphic.
564 # `mapping` is an empty _named_ list, so that it is converted to an object
565 # (not an array) in JSON.
566 mapping = list(x = NULL)[0]
567 ))
568
569 list(
570 panels = panel_info,
571 dims = list(
572 width = width,
573 height =height
574 )
575 )
576 }
577
578 # Given a ggplot_build_gtable object, return a coordmap for it.
579 getGgplotCoordmap <- function(p, width, height, res) {
580 if (!inherits(p, "ggplot_build_gtable"))
581 return(NULL)
582
583 tryCatch({
584 # Get info from built ggplot object
585 panel_info <- find_panel_info(p$build)
586
587 # Get ranges from gtable - it's possible for this to return more elements than
588 # info, because it calculates positions even for panels that aren't present.
589 # This can happen with facet_wrap.
590 ranges <- find_panel_ranges(p$gtable, res)
591
592 for (i in seq_along(panel_info)) {
593 panel_info[[i]]$range <- ranges[[i]]
594 }
595
596 return(
597 list(
598 panels = panel_info,
599 dims = list(
600 width = width,
601 height = height
602 )
603 )
604 )
605
606 }, error = function(e) {
607 # If there was an error extracting info from the ggplot object, just return
608 # a list with the error message.
609 return(structure(list(), error = e$message))
610 })
611 }
612
613
614 find_panel_info <- function(b) {
615 # Structure of ggplot objects changed after 2.1.0. After 2.2.1, there was a
616 # an API for extracting the necessary information.
617 ggplot_ver <- get_package_version("ggplot2")
618
619 if (ggplot_ver > "2.2.1") {
620 find_panel_info_api(b)
621 } else if (ggplot_ver > "2.1.0") {
622 find_panel_info_non_api(b, ggplot_format = "new")
623 } else {
624 find_panel_info_non_api(b, ggplot_format = "old")
625 }
626 }
627
628 # This is for ggplot2>2.2.1, after an API was introduced for extracting
629 # information about the plot object.
630 find_panel_info_api <- function(b) {
631 # Given a built ggplot object, return x and y domains (data space coords) for
632 # each panel.
633 layout <- ggplot2::summarise_layout(b)
634 coord <- ggplot2::summarise_coord(b)
635 layers <- ggplot2::summarise_layers(b)
636
637 `%NA_OR%` <- function(x, y) {
638 if (is_na(x)) y else x
639 }
640
641 # Given x and y scale objects and a coord object, return a list that has
642 # the bases of log transformations for x and y, or NULL if it's not a
643 # log transform.
644 get_log_bases <- function(xscale, yscale, coord) {
645 # Given a transform object, find the log base; if the transform object is
646 # NULL, or if it's not a log transform, return NA.
647 get_log_base <- function(trans) {
648 if (!is.null(trans) && grepl("^log-", trans$name)) {
649 environment(trans$transform)$base
650 } else {
651 NA_real_
652 }
653 }
654
655 # First look for log base in scale, then coord; otherwise NULL.
656 list(
657 x = get_log_base(xscale$trans) %NA_OR% coord$xlog %NA_OR% NULL,
658 y = get_log_base(yscale$trans) %NA_OR% coord$ylog %NA_OR% NULL
659 )
660 }
661
662 # Given x/y min/max, and the x/y scale objects, create a list that
663 # represents the domain. Note that the x/y min/max should be taken from
664 # the layout summary table, not the scale objects.
665 get_domain <- function(xmin, xmax, ymin, ymax, xscale, yscale) {
666 is_reverse <- function(scale) {
667 identical(scale$trans$name, "reverse")
668 }
669
670 domain <- list(
671 left = xmin,
672 right = xmax,
673 bottom = ymin,
674 top = ymax
675 )
676
677 if (is_reverse(xscale)) {
678 domain$left <- -domain$left
679 domain$right <- -domain$right
680 }
681 if (is_reverse(yscale)) {
682 domain$top <- -domain$top
683 domain$bottom <- -domain$bottom
684 }
685
686 domain <- add_discrete_limits(domain, xscale, "x")
687 domain <- add_discrete_limits(domain, yscale, "y")
688
689 domain
690 }
691
692 # Rename the items in vars to have names like panelvar1, panelvar2.
693 rename_panel_vars <- function(vars) {
694 for (i in seq_along(vars)) {
695 names(vars)[i] <- paste0("panelvar", i)
696 }
697 vars
698 }
699
700 get_mappings <- function(layers, layout, coord) {
701 # For simplicity, we'll just use the mapping from the first layer of the
702 # ggplot object. The original uses quoted expressions; convert to
703 # character.
704 mapping <- layers$mapping[[1]]
705 # In ggplot2 <=2.2.1, the mappings are expressions. In later versions, they
706 # are quosures. `deparse(quo_squash(x))` will handle both cases.
707 # as.character results in unexpected behavior for expressions like `wt/2`,
708 # which is why we use deparse.
709 mapping <- lapply(mapping, function(x) deparse(rlang::quo_squash(x)))
710
711 # If either x or y is not present, give it a NULL entry.
712 mapping <- mergeVectors(list(x = NULL, y = NULL), mapping)
713
714 # The names (not values) of panel vars are the same across all panels,
715 # so just look at the first one. Also, the order of panel vars needs
716 # to be reversed.
717 vars <- rev(layout$vars[[1]])
718 for (i in seq_along(vars)) {
719 mapping[[paste0("panelvar", i)]] <- names(vars)[i]
720 }
721
722 if (isTRUE(coord$flip)) {
723 mapping[c("x", "y")] <- mapping[c("y", "x")]
724 }
725
726 mapping
727 }
728
729 # Mapping is constant across all panels, so get it here and reuse later.
730 mapping <- get_mappings(layers, layout, coord)
731
732 # If coord_flip is used, these need to be swapped
733 flip_xy <- function(layout) {
734 l <- layout
735 l$xscale <- layout$yscale
736 l$yscale <- layout$xscale
737 l$xmin <- layout$ymin
738 l$xmax <- layout$ymax
739 l$ymin <- layout$xmin
740 l$ymax <- layout$xmax
741 l
742 }
743 if (coord$flip) {
744 layout <- flip_xy(layout)
745 }
746
747 # Iterate over each row in the layout data frame
748 lapply(seq_len(nrow(layout)), function(i) {
749 # Slice out one row, use it as a list. The (former) list-cols are still
750 # in lists, so we need to unwrap them.
751 l <- as.list(layout[i, ])
752 l$vars <- l$vars[[1]]
753 l$xscale <- l$xscale[[1]]
754 l$yscale <- l$yscale[[1]]
755
756 list(
757 panel = as.numeric(l$panel),
758 row = l$row,
759 col = l$col,
760 # Rename panel vars. They must also be in reversed order.
761 panel_vars = rename_panel_vars(rev(l$vars)),
762 log = get_log_bases(l$xscale, l$yscale, coord),
763 domain = get_domain(l$xmin, l$xmax, l$ymin, l$ymax, l$xscale, l$yscale),
764 mapping = mapping
765 )
766 })
767 }
768
769
770 # This is for ggplot2<=2.2.1, before an API was introduced for extracting
771 # information about the plot object. The "old" format was used before 2.1.0.
772 # The "new" format was used after 2.1.0, up to 2.2.1. The reason these two
773 # formats are mixed together in a single function is historical, and it's not
774 # worthwhile to separate them at this point.
775 find_panel_info_non_api <- function(b, ggplot_format) {
776 # Given a single range object (representing the data domain) from a built
777 # ggplot object, return the domain.
778 find_panel_domain <- function(b, panel_num, scalex_num = 1, scaley_num = 1) {
779 if (ggplot_format == "new") {
780 range <- b$layout$panel_ranges[[panel_num]]
781 } else {
782 range <- b$panel$ranges[[panel_num]]
783 }
784 domain <- list(
785 left = range$x.range[1],
786 right = range$x.range[2],
787 bottom = range$y.range[1],
788 top = range$y.range[2]
789 )
790
791 # Check for reversed scales
792 if (ggplot_format == "new") {
793 xscale <- b$layout$panel_scales$x[[scalex_num]]
794 yscale <- b$layout$panel_scales$y[[scaley_num]]
795 } else {
796 xscale <- b$panel$x_scales[[scalex_num]]
797 yscale <- b$panel$y_scales[[scaley_num]]
798 }
799 if (!is.null(xscale$trans) && xscale$trans$name == "reverse") {
800 domain$left <- -domain$left
801 domain$right <- -domain$right
802 }
803 if (!is.null(yscale$trans) && yscale$trans$name == "reverse") {
804 domain$top <- -domain$top
805 domain$bottom <- -domain$bottom
806 }
807
808 domain <- add_discrete_limits(domain, xscale, "x")
809 domain <- add_discrete_limits(domain, yscale, "y")
810
811 domain
812 }
813
814 # Given built ggplot object, return object with the log base for x and y if
815 # there are log scales or coord transforms.
816 check_log_scales <- function(b, scalex_num = 1, scaley_num = 1) {
817
818 # Given a vector of transformation names like c("log-10", "identity"),
819 # return the first log base, like 10. If none are present, return NULL.
820 extract_log_base <- function(names) {
821 names <- names[grepl("^log-", names)]
822
823 if (length(names) == 0)
824 return(NULL)
825
826 names <- names[1]
827
828 as.numeric(sub("^log-", "", names))
829 }
830
831 # Look for log scales and log coord transforms. People shouldn't use both.
832 x_names <- character(0)
833 y_names <- character(0)
834
835 # Continuous scales have a trans; discrete ones don't
836 if (ggplot_format == "new") {
837 if (!is.null(b$layout$panel_scales$x[[scalex_num]]$trans))
838 x_names <- b$layout$panel_scales$x[[scalex_num]]$trans$name
839 if (!is.null(b$layout$panel_scales$y[[scaley_num]]$trans))
840 y_names <- b$layout$panel_scales$y[[scaley_num]]$trans$name
841
842 } else {
843 if (!is.null(b$panel$x_scales[[scalex_num]]$trans))
844 x_names <- b$panel$x_scales[[scalex_num]]$trans$name
845 if (!is.null(b$panel$y_scales[[scaley_num]]$trans))
846 y_names <- b$panel$y_scales[[scaley_num]]$trans$name
847 }
848
849 coords <- b$plot$coordinates
850 if (!is.null(coords$trans)) {
851 if (!is.null(coords$trans$x))
852 x_names <- c(x_names, coords$trans$x$name)
853 if (!is.null(coords$trans$y))
854 y_names <- c(y_names, coords$trans$y$name)
855 }
856
857 # Keep only scale/trans names that start with "log-"
858 x_names <- x_names[grepl("^log-", x_names)]
859 y_names <- y_names[grepl("^log-", y_names)]
860
861 # Extract the log base from the trans name -- a string like "log-10".
862 list(
863 x = extract_log_base(x_names),
864 y = extract_log_base(y_names)
865 )
866 }
867
868 # Given a built ggplot object, return a named list of variables mapped to x
869 # and y. This function will be called for each panel, but in practice the
870 # result is always the same across panels, so we'll cache the result.
871 mappings_cache <- NULL
872 find_plot_mappings <- function(b) {
873 if (!is.null(mappings_cache))
874 return(mappings_cache)
875
876 # lapply'ing as.character results in unexpected behavior for expressions
877 # like `wt/2`. This works better.
878 mappings <- as.list(as.character(b$plot$mapping))
879
880 # If x or y mapping is missing, look in each layer for mappings and return
881 # the first one.
882 missing_mappings <- setdiff(c("x", "y"), names(mappings))
883 if (length(missing_mappings) != 0) {
884 # Grab mappings for each layer
885 layer_mappings <- lapply(b$plot$layers, function(layer) {
886 lapply(layer$mapping, as.character)
887 })
888
889 # Get just the first x or y value in the combined list of plot and layer
890 # mappings.
891 mappings <- c(list(mappings), layer_mappings)
892 mappings <- Reduce(x = mappings, init = list(x = NULL, y = NULL),
893 function(init, m) {
894 # Can't use m$x/m$y; you get a partial match with xintercept/yintercept
895 if (is.null(init[["x"]]) && !is.null(m[["x"]])) init$x <- m[["x"]]
896 if (is.null(init[["y"]]) && !is.null(m[["y"]])) init$y <- m[["y"]]
897 init
898 }
899 )
900 }
901
902 # Look for CoordFlip
903 if (inherits(b$plot$coordinates, "CoordFlip")) {
904 mappings[c("x", "y")] <- mappings[c("y", "x")]
905 }
906
907 mappings_cache <<- mappings
908 mappings
909 }
910
911 if (ggplot_format == "new") {
912 layout <- b$layout$panel_layout
913 } else {
914 layout <- b$panel$layout
915 }
916 # Convert factor to numbers
917 layout$PANEL <- as.integer(as.character(layout$PANEL))
918
919 # Names of facets
920 facet_vars <- NULL
921 if (ggplot_format == "new") {
922 facet <- b$layout$facet
923 if (inherits(facet, "FacetGrid")) {
924 facet_vars <- vapply(c(facet$params$cols, facet$params$rows), as.character, character(1))
925 } else if (inherits(facet, "FacetWrap")) {
926 facet_vars <- vapply(facet$params$facets, as.character, character(1))
927 }
928 } else {
929 facet <- b$plot$facet
930 if (inherits(facet, "grid")) {
931 facet_vars <- vapply(c(facet$cols, facet$rows), as.character, character(1))
932 } else if (inherits(facet, "wrap")) {
933 facet_vars <- vapply(facet$facets, as.character, character(1))
934 }
935 }
936
937 # Iterate over each row in the layout data frame
938 lapply(seq_len(nrow(layout)), function(i) {
939 # Slice out one row
940 l <- layout[i, ]
941
942 scale_x <- l$SCALE_X
943 scale_y <- l$SCALE_Y
944
945 mapping <- find_plot_mappings(b)
946
947 # For each of the faceting variables, get the value of that variable in
948 # the current panel. Default to empty _named_ list so that it's sent as a
949 # JSON object, not array.
950 panel_vars <- list(a = NULL)[0]
951 for (i in seq_along(facet_vars)) {
952 var_name <- facet_vars[[i]]
953 vname <- paste0("panelvar", i)
954
955 mapping[[vname]] <- var_name
956 panel_vars[[vname]] <- l[[var_name]]
957 }
958
959 list(
960 panel = l$PANEL,
961 row = l$ROW,
962 col = l$COL,
963 panel_vars = panel_vars,
964 scale_x = scale_x,
965 scale_y = scale_x,
966 log = check_log_scales(b, scale_x, scale_y),
967 domain = find_panel_domain(b, l$PANEL, scale_x, scale_y),
968 mapping = mapping
969 )
970 })
971 }
972
973 # Use public API for getting the unit's type (grid::unitType(), added in R 4.0)
974 # https://github.com/wch/r-source/blob/f9b8a42/src/library/grid/R/unit.R#L179
975 getUnitType <- function(u) {
976 tryCatch(
977 get("unitType", envir = asNamespace("grid"))(u),
978 error = function(e) attr(u, "unit", exact = TRUE)
979 )
980 }
981
982 # Given a gtable object, return the x and y ranges (in pixel dimensions)
983 find_panel_ranges <- function(g, res) {
984 # Given a vector of unit objects, return logical vector indicating which ones
985 # are "null" units. These units use the remaining available width/height --
986 # that is, the space not occupied by elements that have an absolute size.
987 is_null_unit <- function(x) {
988 # A vector of units can be either a list of individual units (a unit.list
989 # object), each with their own set of attributes, or an atomic vector with
990 # one set of attributes. ggplot2 switched from the former (in version
991 # 1.0.1) to the latter. We need to make sure that we get the correct
992 # result in both cases.
993 if (inherits(x, "unit.list")) {
994 # For ggplot2 <= 1.0.1
995 vapply(x, FUN.VALUE = logical(1), function(u) {
996 isTRUE(getUnitType(u) == "null")
997 })
998 } else {
999 # For later versions of ggplot2
1000 getUnitType(x) == "null"
1001 }
1002 }
1003
1004 # Workaround for a bug in the quartz device. If you have a 400x400 image and
1005 # run `convertWidth(unit(1, "npc"), "native")`, the result will depend on
1006 # res setting of the device. If res=72, then it returns 400 (as expected),
1007 # but if, e.g., res=96, it will return 300, which is incorrect.
1008 devScaleFactor <- 1
1009 if (grepl("quartz", names(grDevices::dev.cur()), fixed = TRUE)) {
1010 devScaleFactor <- res / 72
1011 }
1012
1013 # Convert a unit (or vector of units) to a numeric vector of pixel sizes
1014 h_px <- function(x) {
1015 devScaleFactor * grid::convertHeight(x, "native", valueOnly = TRUE)
1016 }
1017 w_px <- function(x) {
1018 devScaleFactor * grid::convertWidth(x, "native", valueOnly = TRUE)
1019 }
1020
1021 # Given a vector of relative sizes (in grid units), and a function for
1022 # converting grid units to numeric pixels, return a list with: known pixel
1023 # dimensions, scalable dimensions, and the overall space for the scalable
1024 # objects.
1025 find_size_info <- function(rel_sizes, unit_to_px) {
1026 # Total pixels (in height or width)
1027 total_px <- unit_to_px(grid::unit(1, "npc"))
1028 # Calculate size of all panel(s) together. Panels (and only panels) have
1029 # null size.
1030 null_idx <- is_null_unit(rel_sizes)
1031
1032 # All the absolute heights. At this point, null heights are 0. We need to
1033 # calculate them separately and add them in later.
1034 px_sizes <- unit_to_px(rel_sizes)
1035 # Mark the null heights as NA.
1036 px_sizes[null_idx] <- NA_real_
1037
1038 # The plotting panels all are 'null' units.
1039 null_sizes <- rep(NA_real_, length(rel_sizes))
1040 # Workaround for `[.unit` forbidding zero-length subsets
1041 # https://github.com/wch/r-source/blob/f9b8a42/src/library/grid/R/unit.R#L448-L450
1042 if (length(null_idx)) {
1043 null_sizes[null_idx] <- as.numeric(rel_sizes[null_idx])
1044 }
1045
1046 # Total size allocated for panels is the total image size minus absolute
1047 # (non-panel) elements.
1048 panel_px_total <- total_px - sum(px_sizes, na.rm = TRUE)
1049
1050 # Size of a 1null unit
1051 null_px <- abs(panel_px_total / sum(null_sizes, na.rm = TRUE))
1052
1053 # This returned list contains:
1054 # * px_sizes: A vector of known pixel dimensions. The values that were
1055 # null units will be assigned NA. The null units are ones that scale
1056 # when the plotting area is resized.
1057 # * null_sizes: A vector of the null units. All others will be assigned
1058 # NA. The null units often are 1, but they may be any value, especially
1059 # when using coord_fixed.
1060 # * null_px: The size (in pixels) of a 1null unit.
1061 # * null_px_scaled: The size (in pixels) of a 1null unit when scaled to
1062 # fit a smaller dimension (used for plots with coord_fixed).
1063 list(
1064 px_sizes = abs(px_sizes),
1065 null_sizes = null_sizes,
1066 null_px = null_px,
1067 null_px_scaled = null_px
1068 )
1069 }
1070
1071 # Given a size_info, return absolute pixel positions
1072 size_info_to_px <- function(info) {
1073 px_sizes <- info$px_sizes
1074
1075 null_idx <- !is.na(info$null_sizes)
1076 px_sizes[null_idx] <- info$null_sizes[null_idx] * info$null_px_scaled
1077
1078 # If this direction is scaled down because of coord_fixed, we need to add an
1079 # offset so that the pixel locations are centered.
1080 offset <- (info$null_px - info$null_px_scaled) *
1081 sum(info$null_sizes, na.rm = TRUE) / 2
1082
1083 # Get absolute pixel positions
1084 cumsum(px_sizes) + offset
1085 }
1086
1087 heights_info <- find_size_info(g$heights, h_px)
1088 widths_info <- find_size_info(g$widths, w_px)
1089
1090 if (g$respect) {
1091 # This is a plot with coord_fixed. The grid 'respect' option means to use
1092 # the same pixel value for 1null, for width and height. We want the
1093 # smaller of the two values -- that's what makes the plot fit in the
1094 # viewport.
1095 null_px_min <- min(heights_info$null_px, widths_info$null_px)
1096 heights_info$null_px_scaled <- null_px_min
1097 widths_info$null_px_scaled <- null_px_min
1098 }
1099
1100 # Convert to absolute pixel positions
1101 y_pos <- size_info_to_px(heights_info)
1102 x_pos <- size_info_to_px(widths_info)
1103
1104 # Match up the pixel dimensions to panels
1105 layout <- g$layout
1106 # For panels:
1107 # * For facet_wrap, they'll be named "panel-1", "panel-2", etc.
1108 # * For no facet or facet_grid, they'll just be named "panel". For
1109 # facet_grid, we need to re-order the layout table. Assume that panel
1110 # numbers go from left to right, then next row.
1111 # Assign a number to each panel, corresponding to PANEl in the built ggplot
1112 # object.
1113 layout <- layout[grepl("^panel", layout$name), ]
1114 layout <- layout[order(layout$t, layout$l), ]
1115 layout$panel <- seq_len(nrow(layout))
1116
1117 # Return list of lists, where each inner list has left, right, top, bottom
1118 # values for a panel
1119 lapply(seq_len(nrow(layout)), function(i) {
1120 p <- layout[i, , drop = FALSE]
1121 list(
1122 left = x_pos[p$l - 1],
1123 right = x_pos[p$r],
1124 bottom = y_pos[p$b],
1125 top = y_pos[p$t - 1]
1126 )
1127 })
1128 }
1129
1130 # Remember the x/y limits of discrete axes. This info is
1131 # necessary to properly inverse map the numeric (i.e., trained)
1132 # positions back to the data scale, for example:
1133 # https://github.com/rstudio/shiny/pull/2410#issuecomment-487783828
1134 # https://github.com/rstudio/shiny/pull/2410#issuecomment-488100881
1135 #
1136 # Eventually, we may want to consider storing the entire ggplot2
1137 # object server-side and querying information from that object
1138 # as we need it...that's the only way we'll ever be able to
1139 # faithfully brush examples like this:
1140 # https://github.com/rstudio/shiny/issues/2411
1141 add_discrete_limits <- function(domain, scale, var = "x") {
1142 var <- match.arg(var, c("x", "y"))
1143 if (!is.function(scale$is_discrete) || !is.function(scale$get_limits)) return(domain)
1144 if (scale$is_discrete()) {
1145 domain$discrete_limits[[var]] <- scale$get_limits()
1146 }
1147 domain
1148 }