-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathscale-continuous.r
60 lines (55 loc) · 1.87 KB
/
scale-continuous.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#' Continuous scale
#'
#' @param x vector of continuous values to scale
#' @param palette palette to use.
#'
#' Built in palettes:
#' \Sexpr[results=rd,stage=build]{scales:::seealso_pal()}
#' @param na.value value to use for missing values
#' @param trans transformation object describing the how to transform the
#' raw data prior to scaling. Defaults to the identity transformation which
#' leaves the data unchanged.
#'
#' Built in transformations:
#' \Sexpr[results=rd,stage=build]{scales:::seealso_trans()}.
#' @export
#' @examples
#' with(mtcars, plot(disp, mpg, cex = cscale(hp, rescale_pal())))
#' with(mtcars, plot(disp, mpg, cex = cscale(hp, rescale_pal(),
#' trans = sqrt_trans()
#' )))
#' with(mtcars, plot(disp, mpg, cex = cscale(hp, area_pal())))
#' with(mtcars, plot(disp, mpg,
#' pch = 20, cex = 5,
#' col = cscale(hp, seq_gradient_pal("grey80", "black"))
#' ))
cscale <- function(x, palette, na.value = NA_real_, trans = identity_trans()) {
stopifnot(is.trans(trans))
x <- trans$transform(x)
limits <- train_continuous(x)
map_continuous(palette, x, limits, na.value)
}
#' Train (update) a continuous scale
#'
#' Strips attributes and always returns a numeric vector
#'
#' @inheritParams train_discrete
#' @export
train_continuous <- function(new, existing = NULL) {
if (is.null(new)) {
return(existing)
}
if (is.factor(new) || !typeof(new) %in% c("integer", "double")) {
stop("Discrete value supplied to continuous scale", call. = FALSE)
}
suppressWarnings(range(existing, new, na.rm = TRUE, finite = TRUE))
}
# Map values for a continuous palette.
#
# @param oob out of bounds behaviour. Defaults to \code{\link{censor}}
# which turns oob values into missing values.
map_continuous <- function(palette, x, limits, na.value = NA_real_, oob = censor) {
x <- oob(rescale(x, from = limits))
pal <- palette(x)
ifelse(!is.na(x), pal, na.value)
}