Debian Codegraph @

R/image-interact.R

raw
1 #' Find rows of data selected on an interactive plot.
2 #'
3 #' @description
4 #' `brushedPoints()` returns rows from a data frame which are under a brush.
5 #' `nearPoints()` returns rows from a data frame which are near a click, hover,
6 #' or double-click. Alternatively, set `allRows = TRUE` to return all rows from
7 #' the input data with an additional column `selected_` that indicates which
8 #' rows of the would be selected.
9 #'
10 #' @section ggplot2:
11 #' For plots created with ggplot2, it is not necessary to specify the
12 #' column names to `xvar`, `yvar`, `panelvar1`, and `panelvar2` as that
13 #' information can be automatically derived from the plot specification.
14 #'
15 #' Note, however, that this will not work if you use a computed column, like
16 #' `aes(speed/2, dist))`. Instead, we recommend that you modify the data
17 #' first, and then make the plot with "raw" columns in the modified data.
18 #'
19 #' @section Brushing:
20 #' If x or y column is a factor, then it will be coerced to an integer vector.
21 #' If it is a character vector, then it will be coerced to a factor and then
22 #' integer vector. This means that the brush will be considered to cover a
23 #' given character/factor value when it covers the center value.
24 #'
25 #' If the brush is operating in just the x or y directions (e.g., with
26 #' `brushOpts(direction = "x")`, then this function will filter out points
27 #' using just the x or y variable, whichever is appropriate.
28 #'
29 #' @returns
30 #' A data frame based on `df`, containing the observations selected by the
31 #' brush or near the click event. For `nearPoints()`, the rows will be sorted
32 #' by distance to the event.
33 #'
34 #' If `allRows = TRUE`, then all rows will returned, along with a new
35 #' `selected_` column that indicates whether or not the point was selected.
36 #' The output from `nearPoints()` will no longer be sorted, but you can
37 #' set `addDist = TRUE` to get an additional column that gives the pixel
38 #' distance to the pointer.
39 #'
40 #' @param df A data frame from which to select rows.
41 #' @param brush,coordinfo The data from a brush or click/dblclick/hover event
42 #' e.g. `input$plot_brush`, `input$plot_click`.
43 #' @param xvar,yvar A string giving the name of the variable on the x or y axis.
44 #' These are only required for base graphics, and must be the name of
45 #' a column in `df`.
46 #' @param panelvar1,panelvar2 A string giving the name of a panel variable.
47 #' For expert use only; in most cases these will be automatically
48 #' derived from the ggplot2 spec.
49 #' @param allRows If `FALSE` (the default) return a data frame containing
50 #' the selected rows. If `TRUE`, the input data frame will have a new
51 #' column, `selected_`, which indicates whether the row was selected or not.
52 #' @param threshold A maximum distance (in pixels) to the pointer location.
53 #' Rows in the data frame will be selected if the distance to the pointer is
54 #' less than `threshold`.
55 #' @param maxpoints Maximum number of rows to return. If `NULL` (the default),
56 #' will return all rows within the threshold distance.
57 #' @param addDist If TRUE, add a column named `dist_` that contains the
58 #' distance from the coordinate to the point, in pixels. When no pointer
59 #' event has yet occurred, the value of `dist_` will be `NA`.
60 #' @seealso [plotOutput()] for example usage.
61 #' @export
62 #' @examples
63 #' \dontrun{
64 #' # Note that in practice, these examples would need to go in reactives
65 #' # or observers.
66 #'
67 #' # This would select all points within 5 pixels of the click
68 #' nearPoints(mtcars, input$plot_click)
69 #'
70 #' # Select just the nearest point within 10 pixels of the click
71 #' nearPoints(mtcars, input$plot_click, threshold = 10, maxpoints = 1)
72 #'
73 #' }
74 brushedPoints <- function(df, brush, xvar = NULL, yvar = NULL,
75 panelvar1 = NULL, panelvar2 = NULL,
76 allRows = FALSE) {
77 if (is.null(brush)) {
78 if (allRows)
79 df$selected_ <- FALSE
80 else
81 df <- df[0, , drop = FALSE]
82
83 return(df)
84 }
85
86 if (is.null(brush$xmin)) {
87 stop("brushedPoints requires a brush object with xmin, xmax, ymin, and ymax.")
88 }
89
90 # Which direction(s) the brush is selecting over. Direction can be 'x', 'y',
91 # or 'xy'.
92 use_x <- grepl("x", brush$direction)
93 use_y <- grepl("y", brush$direction)
94
95 # We transitioned to using %||% in Shiny 1.6.0. Previously, these vars could
96 # be NA, because the old %OR% operator recognized NA. These warnings and
97 # the NULL replacement are here just to ease the transition in case anyone is
98 # using NA. We can remove these checks in a future version of Shiny.
99 # https://github.com/rstudio/shiny/pull/3172
100 if (is_na(xvar)) { xvar <- NULL; warning("xvar should be NULL, not NA.") }
101 if (is_na(yvar)) { yvar <- NULL; warning("yvar should be NULL, not NA.") }
102 if (is_na(panelvar1)) { panelvar1 <- NULL; warning("panelvar1 should be NULL, not NA.") }
103 if (is_na(panelvar2)) { panelvar2 <- NULL; warning("panelvar2 should be NULL, not NA.") }
104
105 # Try to extract vars from brush object
106 xvar <- xvar %||% brush$mapping$x
107 yvar <- yvar %||% brush$mapping$y
108 panelvar1 <- panelvar1 %||% brush$mapping$panelvar1
109 panelvar2 <- panelvar2 %||% brush$mapping$panelvar2
110
111 # Filter out x and y values
112 keep_rows <- rep(TRUE, nrow(df))
113 if (use_x) {
114 if (is.null(xvar))
115 stop("brushedPoints: not able to automatically infer `xvar` from brush")
116 if (!(xvar %in% names(df)))
117 stop("brushedPoints: `xvar` ('", xvar ,"') not in names of input")
118 keep_rows <- keep_rows & within_brush(df[[xvar]], brush, "x")
119 }
120 if (use_y) {
121 if (is.null(yvar))
122 stop("brushedPoints: not able to automatically infer `yvar` from brush")
123 if (!(yvar %in% names(df)))
124 stop("brushedPoints: `yvar` ('", yvar ,"') not in names of input")
125 keep_rows <- keep_rows & within_brush(df[[yvar]], brush, "y")
126 }
127
128 # Find which rows are matches for the panel vars (if present)
129 if (!is.null(panelvar1))
130 keep_rows <- keep_rows & panelMatch(brush$panelvar1, df[[panelvar1]])
131 if (!is.null(panelvar2))
132 keep_rows <- keep_rows & panelMatch(brush$panelvar2, df[[panelvar2]])
133
134 if (allRows) {
135 df$selected_ <- keep_rows
136 df
137 } else {
138 df[keep_rows, , drop = FALSE]
139 }
140 }
141
142 # The `brush` data structure will look something like the examples below.
143 # For base graphics, `mapping` is empty, and there are no panelvars:
144 # List of 8
145 # $ xmin : num 3.73
146 # $ xmax : num 4.22
147 # $ ymin : num 13.9
148 # $ ymax : num 19.8
149 # $ coords_css:List of 4
150 # ..$ xmin: int 260
151 # ..$ xmax: int 298
152 # ..$ ymin: num 112
153 # ..$ ymax: num 205
154 # $ coords_img:List of 4
155 # ..$ xmin: int 325
156 # ..$ xmax: num 372
157 # ..$ ymin: num 140
158 # ..$ ymax: num 257
159 # $ img_css_ratio:List of 2
160 # ..$ x: num 1.25
161 # ..$ y: num 1.25
162 # $ mapping: Named list()
163 # $ domain :List of 4
164 # ..$ left : num 1.36
165 # ..$ right : num 5.58
166 # ..$ bottom: num 9.46
167 # ..$ top : num 34.8
168 # $ range :List of 4
169 # ..$ left : num 58
170 # ..$ right : num 429
171 # ..$ bottom: num 226
172 # ..$ top : num 58
173 # $ log :List of 2
174 # ..$ x: NULL
175 # ..$ y: NULL
176 # $ direction: chr "y"
177 #
178 # For ggplot2, the mapping vars usually will be included, and if faceting is
179 # used, they will be listed as panelvars:
180 # List of 10
181 # $ xmin : num 3.18
182 # $ xmax : num 3.78
183 # $ ymin : num 17.1
184 # $ ymax : num 20.4
185 # $ panelvar1: chr "6"
186 # $ panelvar2: chr "0
187 # $ coords_css:List of 4
188 # ..$ xmin: int 260
189 # ..$ xmax: int 298
190 # ..$ ymin: num 112
191 # ..$ ymax: num 205
192 # $ coords_img:List of 4
193 # ..$ xmin: int 325
194 # ..$ xmax: num 372
195 # ..$ ymin: num 140
196 # ..$ ymax: num 257
197 # $ img_css_ratio:List of 2
198 # ..$ x: num 1.25
199 # ..$ y: num 1.25
200 # $ mapping :List of 4
201 # ..$ x : chr "wt"
202 # ..$ y : chr "mpg"
203 # ..$ panelvar1: chr "cyl"
204 # ..$ panelvar2: chr "am"
205 # $ domain :List of 4
206 # ..$ left : num 1.32
207 # ..$ right : num 5.62
208 # ..$ bottom: num 9.22
209 # ..$ top : num 35.1
210 # $ range :List of 4
211 # ..$ left : num 172
212 # ..$ right : num 300
213 # ..$ bottom: num 144
214 # ..$ top : num 28.5
215 # $ log :List of 2
216 # ..$ x: NULL
217 # ..$ y: NULL
218 # $ direction: chr "y"
219
220
221 #' @export
222 #' @rdname brushedPoints
223 nearPoints <- function(df, coordinfo, xvar = NULL, yvar = NULL,
224 panelvar1 = NULL, panelvar2 = NULL,
225 threshold = 5, maxpoints = NULL, addDist = FALSE,
226 allRows = FALSE) {
227 if (is.null(coordinfo)) {
228 if (addDist)
229 df$dist_ <- NA_real_
230
231 if (allRows)
232 df$selected_ <- FALSE
233 else
234 df <- df[0, , drop = FALSE]
235
236 return(df)
237 }
238
239 if (is.null(coordinfo$x)) {
240 stop("nearPoints requires a click/hover/double-click object with x and y values.")
241 }
242
243 # We transitioned to using %||% in Shiny 1.6.0. Previously, these vars could
244 # be NA, because the old %OR% operator recognized NA. These warnings and
245 # the NULL replacement are here just to ease the transition in case anyone is
246 # using NA. We can remove these checks in a future version of Shiny.
247 # https://github.com/rstudio/shiny/pull/3172
248 if (is_na(xvar)) { xvar <- NULL; warning("xvar should be NULL, not NA.") }
249 if (is_na(yvar)) { yvar <- NULL; warning("yvar should be NULL, not NA.") }
250 if (is_na(panelvar1)) { panelvar1 <- NULL; warning("panelvar1 should be NULL, not NA.") }
251 if (is_na(panelvar2)) { panelvar2 <- NULL; warning("panelvar2 should be NULL, not NA.") }
252
253 # Try to extract vars from coordinfo object
254 xvar <- xvar %||% coordinfo$mapping$x
255 yvar <- yvar %||% coordinfo$mapping$y
256 panelvar1 <- panelvar1 %||% coordinfo$mapping$panelvar1
257 panelvar2 <- panelvar2 %||% coordinfo$mapping$panelvar2
258
259 if (is.null(xvar))
260 stop("nearPoints: not able to automatically infer `xvar` from coordinfo")
261 if (is.null(yvar))
262 stop("nearPoints: not able to automatically infer `yvar` from coordinfo")
263
264 if (!(xvar %in% names(df)))
265 stop("nearPoints: `xvar` ('", xvar ,"') not in names of input")
266 if (!(yvar %in% names(df)))
267 stop("nearPoints: `yvar` ('", yvar ,"') not in names of input")
268
269 # Extract data values from the data frame
270 coordinfo <- fortifyDiscreteLimits(coordinfo)
271 x <- asNumber(df[[xvar]], coordinfo$domain$discrete_limits$x)
272 y <- asNumber(df[[yvar]], coordinfo$domain$discrete_limits$y)
273
274 # Get the coordinates of the point (in img pixel coordinates)
275 point_img <- coordinfo$coords_img
276
277 # Get coordinates of data points (in img pixel coordinates)
278 data_img <- scaleCoords(x, y, coordinfo)
279
280 # Get x/y distances (in css coordinates)
281 dist_css <- list(
282 x = (data_img$x - point_img$x) / coordinfo$img_css_ratio$x,
283 y = (data_img$y - point_img$y) / coordinfo$img_css_ratio$y
284 )
285
286 # Distances of data points to the target point, in css pixels.
287 dists <- sqrt(dist_css$x^2 + dist_css$y^2)
288
289 if (addDist)
290 df$dist_ <- dists
291
292 keep_rows <- (dists <= threshold)
293
294 # Find which rows are matches for the panel vars (if present)
295 if (!is.null(panelvar1))
296 keep_rows <- keep_rows & panelMatch(coordinfo$panelvar1, df[[panelvar1]])
297 if (!is.null(panelvar2))
298 keep_rows <- keep_rows & panelMatch(coordinfo$panelvar2, df[[panelvar2]])
299
300 # Track the indices to keep
301 keep_idx <- which(keep_rows)
302
303 # Order by distance
304 dists <- dists[keep_idx]
305 keep_idx <- keep_idx[order(dists)]
306
307 # Keep max number of rows
308 if (!is.null(maxpoints) && length(keep_idx) > maxpoints) {
309 keep_idx <- keep_idx[seq_len(maxpoints)]
310 }
311
312 if (allRows) {
313 # Add selected_ column if needed
314 df$selected_ <- FALSE
315 df$selected_[keep_idx] <- TRUE
316
317 } else {
318 # If we don't keep all rows, return just the selected rows, sorted by
319 # distance.
320 df <- df[keep_idx, , drop = FALSE]
321 }
322
323 df
324 }
325
326 # The coordinfo data structure will look something like the examples below.
327 # For base graphics, `mapping` is empty, and there are no panelvars:
328 # List of 7
329 # $ x : num 4.37
330 # $ y : num 12
331 # $ coords_css:List of 2
332 # ..$ x: int 286
333 # ..$ y: int 192
334 # $ coords_img:List of 2
335 # ..$ x: num 358
336 # ..$ y: int 240
337 # $ img_css_ratio:List of 2
338 # ..$ x: num 1.25
339 # ..$ y: num 1.25
340 # $ mapping : Named list()
341 # $ domain :List of 4
342 # ..$ left : num 1.36
343 # ..$ right : num 5.58
344 # ..$ bottom: num 9.46
345 # ..$ top : num 34.8
346 # $ range :List of 4
347 # ..$ left : num 58
348 # ..$ right : num 429
349 # ..$ bottom: num 226
350 # ..$ top : num 58
351 # $ log :List of 2
352 # ..$ x: NULL
353 # ..$ y: NULL
354 # $ .nonce : num 0.343
355 #
356 # For ggplot2, the mapping vars usually will be included, and if faceting is
357 # used, they will be listed as panelvars:
358 # List of 9
359 # $ x : num 3.78
360 # $ y : num 17.1
361 # $ coords_css:List of 2
362 # ..$ x: int 286
363 # ..$ y: int 192
364 # $ coords_img:List of 2
365 # ..$ x: num 358
366 # ..$ y: int 240
367 # $ img_css_ratio:List of 2
368 # ..$ x: num 1.25
369 # ..$ y: num 1.25
370 # $ panelvar1 : chr "6"
371 # $ panelvar2 : chr "0"
372 # $ mapping :List of 4
373 # ..$ x : chr "wt"
374 # ..$ y : chr "mpg"
375 # ..$ panelvar1: chr "cyl"
376 # ..$ panelvar2: chr "am"
377 # $ domain :List of 4
378 # ..$ left : num 1.32
379 # ..$ right : num 5.62
380 # ..$ bottom: num 9.22
381 # ..$ top : num 35.1
382 # $ range :List of 4
383 # ..$ left : num 172
384 # ..$ right : num 300
385 # ..$ bottom: num 144
386 # ..$ top : num 28.5
387 # $ log :List of 2
388 # ..$ x: NULL
389 # ..$ y: NULL
390 # $ .nonce : num 0.603
391
392 # Helper to determine if data values are within the limits of
393 # an input brush
394 within_brush <- function(vals, brush, var = "x") {
395 var <- match.arg(var, c("x", "y"))
396 brush <- fortifyDiscreteLimits(brush)
397 vals <- asNumber(vals, brush$domain$discrete_limits[[var]])
398 # It's possible for a non-missing data values to not
399 # map to the axis limits, for example:
400 # https://github.com/rstudio/shiny/pull/2410#issuecomment-488100881
401 !is.na(vals) &
402 vals >= brush[[paste0(var, "min")]] &
403 vals <= brush[[paste0(var, "max")]]
404 }
405
406 # Coerce various types of variables to numbers. This works for Date, POSIXt,
407 # characters, and factors. Used because the mouse coords are numeric.
408 # The `levels` argument should be used when mapping this variable to
409 # a known set of discrete levels, which is needed for ggplot2 since
410 # it allows you to control ordering and possible values of a discrete
411 # positional scale (#2410)
412 asNumber <- function(x, levels = NULL) {
413 if (length(levels)) return(match(x, levels))
414 if (is.character(x)) x <- as.factor(x)
415 if (is.factor(x)) x <- as.integer(x)
416 as.numeric(x)
417 }
418
419 # Ensure the discrete limits/levels of a coordmap received
420 # from the client matches the data structure sent the client.
421 #
422 # When we construct the coordmap (in getGgplotCoordmap()),
423 # we save a character vector which may contain missing values
424 # (e.g., c("a", "b", NA)). When that same character is received
425 # from the client, it runs through decodeMessage() which sets
426 # simplifyVector=FALSE, which means NA are replaced by NULL
427 # (because jsonlite::fromJSON('["a", "b", null]') -> list("a", "b", NULL))
428 #
429 # Thankfully, it doesn't seem like it's meaningful for limits to
430 # contains a NULL in the 1st place, so we simply treat NULL like NA.
431 # For more context, https://github.com/rstudio/shiny/issues/2666
432 fortifyDiscreteLimits <- function(coord) {
433 # Note that discrete_limits$x/y are populated iff
434 # x/y are discrete mappings
435 coord$domain$discrete_limits <- lapply(
436 coord$domain$discrete_limits,
437 function(var) {
438 # if there is an 'explicit' NULL, then the limits are NA
439 if (is.null(var)) return(NA)
440 vapply(var, function(x) {
441 if (is.null(x) || isTRUE(is.na(x))) NA_character_ else x
442 }, character(1))
443 }
444 )
445 coord
446 }
447
448
449
450 # Given a panelvar value and a vector x, return logical vector indicating which
451 # items match the panelvar value. Because the panelvar value is always a
452 # string but the vector could be numeric, it might be necessary to coerce the
453 # panelvar to a number before comparing to the vector.
454 panelMatch <- function(search_value, x) {
455 if (is.null(search_value)) return(is.na(x))
456 if (is.numeric(x)) search_value <- as.numeric(search_value)
457 x == search_value
458 }
459
460 # ----------------------------------------------------------------------------
461 # Scaling functions
462 # These functions have direct analogs in Javascript code, except these are
463 # vectorized for x and y.
464
465 # Map a value x from a domain to a range. If clip is true, clip it to the
466 # range.
467 mapLinear <- function(x, domainMin, domainMax, rangeMin, rangeMax, clip = TRUE) {
468 factor <- (rangeMax - rangeMin) / (domainMax - domainMin)
469 val <- x - domainMin
470 newval <- (val * factor) + rangeMin
471
472 if (clip) {
473 maxval <- max(rangeMax, rangeMin)
474 minval <- min(rangeMax, rangeMin)
475 newval[newval > maxval] <- maxval
476 newval[newval < minval] <- minval
477 }
478 newval
479 }
480
481 # Scale val from domain to range. If logbase is present, use log scaling.
482 scale1D <- function(val, domainMin, domainMax, rangeMin, rangeMax,
483 logbase = NULL, clip = TRUE) {
484 if (!is.null(logbase))
485 val <- log(val, logbase)
486 mapLinear(val, domainMin, domainMax, rangeMin, rangeMax, clip)
487 }
488
489 # Inverse scale val, from range to domain. If logbase is present, use inverse
490 # log (power) transformation.
491 scaleInv1D <- function(val, domainMin, domainMax, rangeMin, rangeMax,
492 logbase = NULL, clip = TRUE) {
493 res <- mapLinear(val, rangeMin, rangeMax, domainMin, domainMax, clip)
494 if (!is.null(logbase))
495 res <- logbase ^ res
496 res
497 }
498
499 # Scale x and y coordinates from domain to range, using information in
500 # scaleinfo. scaleinfo must contain items $domain, $range, and $log. The
501 # scaleinfo object corresponds to one element from the coordmap object generated
502 # by getPrevPlotCoordmap or getGgplotCoordmap; it is the scaling information for
503 # one panel in a plot.
504 scaleCoords <- function(x, y, scaleinfo) {
505 if (is.null(scaleinfo))
506 return(NULL)
507
508 domain <- scaleinfo$domain
509 range <- scaleinfo$range
510 log <- scaleinfo$log
511
512 list(
513 x = scale1D(x, domain$left, domain$right, range$left, range$right, log$x),
514 y = scale1D(y, domain$bottom, domain$top, range$bottom, range$top, log$y)
515 )
516 }
517
518 # Inverse scale x and y coordinates from range to domain, using information in
519 # scaleinfo.
520 scaleInvCoords <- function(x, y, scaleinfo) {
521 if (is.null(scaleinfo))
522 return(NULL)
523
524 domain <- scaleinfo$domain
525 range <- scaleinfo$range
526 log <- scaleinfo$log
527
528 list(
529 x = scaleInv1D(x, domain$left, domain$right, range$left, range$right, log$x),
530 y = scaleInv1D(y, domain$bottom, domain$top, range$bottom, range$top, log$y)
531 )
532 }