Debian Codegraph @

R/lighten.R

raw
1 #' Algorithmically Lighten or Darken Colors
2 #'
3 #' The functions \code{lighten} and \code{darken} take a vector of R colors and adjust the colors such that
4 #' they appear lightened or darkened, respectively.
5 #'
6 #' The color adjustment can be calculated in three different color spaces. \enumerate{
7 #' \item If \code{space = "HCL"}, the colors are transformed to HCL, (\code{\link[colorspace]{polarLUV}}),
8 #' the luminance component L is adjusted, and then the colors are transformed back to a hexadecimal
9 #' RGB string.
10 #' \item If \code{space = "HLS"}, the colors are transformed to HLS, the lightness component L is adjusted,
11 #' and then the color is transformed back to a hexadecimal RGB string.
12 #' \item If \code{space = "combined"}, the colors are first adjusted in both the HCL and HLS spaces. Then,
13 #' the adjusted HLS colors are converted into HCL, and then the chroma components of the adjusted HLS
14 #' colors are copied to the adjusted HCL colors. Thus, in effect, the combined model adjusts luminance
15 #' in HCL space but chroma in HLS space.
16 #' }
17 #' We have found that typically \code{space = "HCL"} performs best for lightening colors and \code{space = "combined"}
18 #' performs best for darkening colors, and these are the default settings for \code{lighten} and \code{darken},
19 #' respectively.
20 #'
21 #' Regardless of the chosen color space, the adjustment of the L component can occur by two methods, relative
22 #' (the default) and absolute. Under the absolute method, the adjustment is \code{L +/- 100 * amount} when
23 #' lightening/darkening colors. Under the relative method, the adjustment is \code{100 - (100 - L) * (1 - amount)} when
24 #' lightening colors and \code{L * (1 - amount)} when darkening colors.
25 #'
26 #' Programmatically lightening and darkening colors can yield unexpected results (see examples). In HCL space,
27 #' colors can become either too gray or overly colorful. By contrast, in HLS space it can happen that the
28 #' overall amount of lightening or darkening appears to be non-uniform among a group of colors that are
29 #' lightened or darkened jointly, and again, colors can become either too gray or overly colorful. We
30 #' recommend to try different color spaces if the default space for the chosen function (\code{lighten}
31 #' or \code{darken}) does not look right in a specific application.
32 #'
33 #' @param col vector of any of the three kind of R colors, i.e., either a color
34 #' name (an element of \code{\link[grDevices]{colors}}), a hexadecimal string
35 #' of the form \code{"#rrggbb"} or \code{"#rrggbbaa"} (see
36 #' \code{\link[grDevices]{rgb}}), or an integer \code{i} meaning
37 #' \code{palette()[i]}.
38 #' @param amount numeric specifying the amount of lightening. This is applied either
39 #' multiplicatively or additively to the luminance value, depending on the
40 #' setting of \code{method} (either relative or absolute). Negative numbers
41 #' cause darkening.
42 #' @param method character string specifying the adjustment method. Can be either \code{"relative"} or \code{"absolute"}.
43 #' @param space character string specifying the color space in which adjustment happens. Can be either \code{"HLS"} or \code{"HCL"}.
44 #' @param fixup logical If set to \code{TRUE}, colors that fall outside of the RGB color gamut are slightly modified
45 #' by translating individual primary values so they lie between 0 and 255. If set to \code{FALSE}, out-of-gamut colors
46 #' are replaced by \code{NA}.
47 #' @return A character vector with (s)RGB codings of the colors in the palette.
48 #' @seealso \code{\link[colorspace]{polarLUV}}, \code{\link[colorspace]{hex}}, \code{\link[colorspace]{desaturate}}
49 #' @references Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020).
50 #' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.}
51 #' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49. \doi{10.18637/jss.v096.i01}
52 #' @keywords color
53 #' @examples
54 #' # lighten dark colors, example 1
55 #' cl <- qualitative_hcl(5)
56 #' swatchplot(list(
57 #' HCL = rbind("0%" = cl,
58 #' "15%" = lighten(cl, 0.15),
59 #' "30%" = lighten(cl, 0.3)),
60 #' HLS = rbind("0%" = cl,
61 #' "15%" = lighten(cl, 0.15, space = "HLS"),
62 #' "30%" = lighten(cl, 0.3, space = "HLS")),
63 #' combined = rbind("0%" = cl,
64 #' "15%" = lighten(cl, 0.15, space = "combined"),
65 #' "30%" = lighten(cl, 0.3, space = "combined"))),
66 #' nrow = 4, line = 2.5
67 #' )
68 #'
69 #' # lighten dark colors, example 2
70 #' cl <- c("#61A9D9", "#ADD668", "#E6D152", "#CE6BAF", "#797CBA")
71 #' swatchplot(list(
72 #' HCL = rbind("0%" = cl,
73 #' "15%" = lighten(cl, 0.15),
74 #' "30%" = lighten(cl, 0.3)),
75 #' HLS = rbind("0%" = cl,
76 #' "15%" = lighten(cl, 0.15, space = "HLS"),
77 #' "30%" = lighten(cl, 0.3, space = "HLS")),
78 #' combined = rbind("0%" = cl,
79 #' "15%" = lighten(cl, 0.15, space = "combined"),
80 #' "30%" = lighten(cl, 0.3, space = "combined"))),
81 #' nrow = 4, line = 2.5
82 #' )
83 #'
84 #' # darken light colors, example 1
85 #' cl <- qualitative_hcl(5, "Pastel 1")
86 #' swatchplot(list(
87 #' combined = rbind("0%" = cl,
88 #' "15%" = darken(cl, 0.15),
89 #' "30%" = darken(cl, 0.3)),
90 #' HCL = rbind("0%" = cl,
91 #' "15%" = darken(cl, 0.15, space = "HCL"),
92 #' "30%" = darken(cl, 0.3, space = "HCL")),
93 #' HLS = rbind("0%" = cl,
94 #' "15%" = darken(cl, 0.15, space = "HLS"),
95 #' "30%" = darken(cl, 0.3, space = "HLS"))),
96 #' nrow = 4, line = 2.5
97 #' )
98 #'
99 #' # darken light colors, example 2
100 #' cl <- c("#CDE4F3","#E7F3D3","#F7F0C7","#EFCFE5","#D0D1E7")
101 #' swatchplot(list(
102 #' combined = rbind("0%" = cl,
103 #' "15%" = darken(cl, 0.15),
104 #' "30%" = darken(cl, 0.3)),
105 #' HCL = rbind("0%" = cl,
106 #' "15%" = darken(cl, 0.15, space = "HCL"),
107 #' "30%" = darken(cl, 0.3, space = "HCL")),
108 #' HLS = rbind("0%" = cl,
109 #' "15%" = darken(cl, 0.15, space = "HLS"),
110 #' "30%" = darken(cl, 0.3, space = "HLS"))),
111 #' nrow = 4, line = 2.5
112 #' )
113 #' @export lighten
114 #' @importFrom grDevices rgb
115 #' @importFrom grDevices col2rgb
116 lighten <- function(col, amount = 0.1,
117 method = c("relative", "absolute"), space = c("HCL", "HLS", "combined"), fixup = TRUE)
118 {
119 ## method
120 space <- match.arg(space, c("HCL", "HLS", "combined"))
121 method <- match.arg(method, c("relative", "absolute"))
122
123 ## number of colors
124 n <- max(c(length(col), length(amount)))
125 if(length(col) != n) col <- rep_len(col, length.out = n)
126 if(length(amount) != n) amount <- rep_len(amount, length.out = n)
127
128 ## save original colors for later, to substitute any cases with amount == 0
129 col_orig <- col
130
131 ## col has to be hex code, otherwise col2rgb is used
132 if(is.character(col) && inherits(col, "colors")) col <- as.character(col) ## workaround for prismatic colors class
133 if(is.character(col) &&
134 (all(substr(col, 1L, 1L) == "#") & all(nchar(col) %in% c(7L, 9L))))
135 {
136 ## extract alpha from hex (if any)
137 alpha <- substr(col, 8L, 9L)
138 ## retain only RGB in hex
139 col <- substr(col, 1L, 7L)
140 ## convert to colorspace::RGB
141 col <- hex2RGB(col)
142 } else {
143 col <- col2rgb(col, alpha = TRUE)
144 # save original colors in hex format, in case some were specified as
145 # named colors or as palette entries
146 col_orig <- rgb(t(col), maxColorValue = 255)
147 ## extract alpha values (if non-FF)
148 alpha <- format(as.hexmode(col[4L, ]), width = 2L, upper.case = TRUE)
149 alpha[alpha == "FF"] <- ""
150 ## retain only sRGB
151 col <- sRGB(t(col[1L:3L, ])/255)
152 }
153
154 if (space == "HCL") {
155 ## *** darkening/lightening in HCL space ***
156
157 ## convert to HCL
158 col <- as(col, "polarLUV")
159 ## fix-up extreme luminance cases
160 col@coords[, "L"] <- pmin(100, pmax(0, col@coords[, "L"]))
161
162 ## adjust luminance
163 Lold <- col@coords[, "L"]
164 col@coords[, "L"] <- if(method == "relative") {
165 (amount >= 0) * (100 - (100 - Lold) * (1 - amount)) +
166 (amount < 0) * Lold * (1 + amount)
167 } else {
168 Lold + amount * 100
169 }
170 col@coords[, "L"] <- pmin(100, pmax(0, col@coords[, "L"]))
171
172 ## transform chroma correspondingly (relative to maximum chroma possible)
173 ## It seems better to not apply this adjustment here. Lighened colors look better without it,
174 ## and darkened colors look better under the combined model.
175 #col@coords[, "C"] <- col@coords[, "C"]/ceiling(max_chroma(col@coords[, "H"], Lold) + 1e-8) *
176 # max_chroma(col@coords[, "H"], col@coords[, "L"], floor = TRUE)
177
178 ## check that resulting chroma is within appropriate bounds
179 col@coords[, "C"] <- pmin(max_chroma(col@coords[, "H"], col@coords[, "L"], floor = TRUE),
180 pmax(0, col@coords[, "C"]))
181 }
182 else if (space == "HLS") {
183 ## *** darkening/lightening in HLS space ***
184
185 col <- as(col, "HLS")
186 col@coords[, "L"] <- if(method == "relative") {
187 (amount >= 0) * (1 - (1 - col@coords[, "L"]) * (1 - amount)) +
188 (amount < 0) * col@coords[, "L"] * (1 + amount)
189 } else {
190 col@coords[, "L"] + amount
191 }
192 col@coords[, "L"] <- pmin(1, pmax(0, col@coords[, "L"]))
193 } else {
194 ## *** darkening/lightening in combined space ***
195
196 ## first do adjustment in HLS space
197 colHLS <- as(col, "HLS")
198 colHLS@coords[, "L"] <- if(method == "relative") {
199 (amount >= 0) * (1 - (1 - colHLS@coords[, "L"]) * (1 - amount)) +
200 (amount < 0) * colHLS@coords[, "L"] * (1 + amount)
201 } else {
202 colHLS@coords[, "L"] + amount
203 }
204 colHLS@coords[, "L"] <- pmin(1, pmax(0, colHLS@coords[, "L"]))
205
206 colHLSHCL <- as(as(colHLS, "RGB"), "polarLUV")
207
208 ## now do adjustment in HCL space
209 col <- as(col, "polarLUV")
210 ## fix-up extreme luminance cases
211 col@coords[, "L"] <- pmin(100, pmax(0, col@coords[, "L"]))
212
213 ## transform luminance
214 Lold <- col@coords[, "L"]
215 col@coords[, "L"] <- if(method == "relative") {
216 (amount >= 0) * (100 - (100 - Lold) * (1 - amount)) +
217 (amount < 0) * Lold * (1 + amount)
218 } else {
219 Lold + amount * 100
220 }
221
222 ## fix-up L and copy C over from HLS-converted color
223 col@coords[, "L"] <- pmin(100, pmax(0, col@coords[, "L"]))
224 #col@coords[, "H"] <- colHLSHCL@coords[, "H"]
225 col@coords[, "C"] <- colHLSHCL@coords[, "C"]
226
227 ## make sure chroma is in allowed range
228 col@coords[, "C"] <- pmin(max_chroma(col@coords[, "H"], col@coords[, "L"], floor = TRUE), col@coords[, "C"])
229 }
230
231 ## convert back to hex and add alpha again (if any)
232 col <- hex(col, fixup = fixup)
233 col[!is.na(col)] <- paste(col[!is.na(col)], alpha[!is.na(col)], sep = "")
234
235 ## return original colors whenever amount == 0
236 col[amount == 0] <- col_orig[amount == 0]
237
238 ## preserve names and colors class attribute (if any)
239 if(!is.null(names(col_orig))) names(col) <- names(col_orig)
240 if(identical(attr(col_orig, "class"), "colors")) attr(col, "class") <- "colors" ## workaround for prismatic colors class
241
242 return(col)
243 }
244
245
246 #' @rdname lighten
247 #' @param ... Other parameters handed to the function \code{lighten()}.
248 #' @export
249 darken <- function(col, amount = 0.1, space = "combined", ...)
250 {
251 lighten(col, amount = -1 * amount, space = space, ...)
252 }