Debian Codegraph @

R/hclplot.R

raw
1 #' Palette Plot in HCL Space
2 #'
3 #' Visualization of color palettes in HCL space projections.
4 #'
5 #' The function \code{hclplot} is an auxiliary function for illustrating
6 #' the trajectories of color palettes in two-dimensional HCL space projections.
7 #' It collapses over one of the three coordinates (either the hue H or the
8 #' luminance L) and displays a heatmap of colors combining the remaining
9 #' two dimensions. The coordinates for the given color palette are highlighted
10 #' to bring out its trajectory.
11 #'
12 #' The function \code{hclplot} has been designed to work well with the
13 #' \code{\link{hcl_palettes}} in this package. While it is possible to apply
14 #' it to other color palettes as well, the results might look weird or confusing
15 #' if these palettes are constructed very differently (e.g., as in the highly
16 #' saturated base R palettes).
17 #'
18 #' More specifically, the following palettes can be visualized well: \itemize{
19 #' \item Qualitative with (approximately) constant luminance. In this case,
20 #' \code{hclplot} shows a hue-chroma plane (in polar coordinates), keeping
21 #' luminance at a fixed level (by default displayed in the main title of
22 #' the plot). If the luminance is, in fact, not approximately constant,
23 #' the luminance varies along with hue and chroma, using a simple linear
24 #' function (fitted by least squares).
25 # \item Sequential with (approximately) constant hue. In this case,
26 #' \code{hclplot} shows a chroma-luminance plane, keeping hue at a fixed
27 #' level (by default displayed in the main title of the plot). If the hue
28 #' is, in fact, not approximately constant, the hue varies along with
29 #' chroma and luminance, using a simple linear function (fitted by least
30 #' squares.
31 #' \item Diverging with two (approximately) constant hues: This case is
32 #' visualized with two back-to-back sequential displays.
33 #' }
34 #' To infer the type of display to use, by default, the following heuristic is
35 #' used: If luminance is not approximately constant (range > 10) and follows
36 #' rougly a triangular pattern, a diverging display is used. If luminance is
37 #' not constant and follows roughly a linear pattern, a sequential display is
38 #' used. Otherwise a qualitative display is used.
39 #'
40 #' @param x character vector containing color hex codes, or a \code{\link{color-class}}
41 #' object.
42 #' @param type type character specifying which type of palette should be visualized
43 #' (\code{"qualitative"}, \code{"sequential"}, or \code{"diverging"}).
44 #' For qualitative palettes a hue-chroma plane is used, otherwise a chroma-luminance plane.
45 #' By default, the \code{type} is inferred from the luminance trajectory corresponding
46 #' to \code{x}.
47 #' @param h numeric hue(s) to be used for \code{type = "sequential"} and \code{type = "diverging"}.
48 #' By default, these are inferred from the colors in \code{x}.
49 #' @param c numeric. Maximal chroma value to be used.
50 #' @param l numeric luminance(s) to be used for \code{type = "qualitative"}.
51 #' By default, this is inferred from the colors in \code{x}.
52 #' @param xlab,ylab,main character strings for annotation, by default generated from
53 #' the type of color palette visualized.
54 #' @param cex numeric character extension.
55 #' @param axes logical. Should axes be drawn?
56 #' @param bg,lwd,size graphical control parameters for the color palette trajectory.
57 #' @param \dots currently not used.
58 #'
59 #' @return \code{hclplot} invisibly returns a matrix with the HCL coordinates corresponding to \code{x}.
60 #' @seealso \code{\link{specplot}}
61 #' @references Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020).
62 #' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.}
63 #' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49. \doi{10.18637/jss.v096.i01}
64 #' @keywords hplot
65 #' @examples
66 #' ## for qualitative palettes luminance and chroma are fixed, varying only hue
67 #' hclplot(qualitative_hcl(9, c = 50, l = 70))
68 #'
69 #' ## single-hue sequential palette (h = 260) with linear vs. power-transformed trajectory
70 #' hclplot(sequential_hcl(7, h = 260, c = 80, l = c(35, 95), power = 1))
71 #' hclplot(sequential_hcl(7, h = 260, c = 80, l = c(35, 95), power = 1.5))
72 #'
73 #' ## advanced single-hue sequential palette with triangular chroma trajectory
74 #' ## (piecewise linear vs. power-transformed)
75 #' hclplot(sequential_hcl(7, h = 245, c = c(40, 75, 0), l = c(30, 95), power = 1))
76 #' hclplot(sequential_hcl(7, h = 245, c = c(40, 75, 0), l = c(30, 95), power = c(0.8, 1.4)))
77 #'
78 #' ## multi-hue sequential palette with small hue range and triangular chroma vs.
79 #' ## large hue range and linear chroma trajectory
80 #' hclplot(sequential_hcl(7, h = c(260, 220), c = c(50, 75, 0), l = c(30, 95), power = 1))
81 #' hclplot(sequential_hcl(7, h = c(260, 60), c = 60, l = c(40, 95), power = 1))
82 #'
83 #' ## balanced diverging palette constructed from two simple single-hue sequential
84 #' ## palettes (for hues 260/blue and 0/red)
85 #' hclplot(diverging_hcl(7, h = c(260, 0), c = 80, l = c(35, 95), power = 1))
86 #'
87 #' @export hclplot
88 #' @importFrom graphics box lines mtext par plot points rect text
89 #' @importFrom stats cor lm median predict
90 hclplot <- function(x, type = NULL, h = NULL, c = NULL, l = NULL,
91 xlab = NULL, ylab = NULL, main = NULL, cex = 1.0, axes = TRUE,
92 bg = "white", lwd = 1, size = 2.5, ...)
93 {
94
95 ## TODO: Not yet able to handle NA values. Thus, replace
96 ## NA values with white, if needed.
97 NAidx <- which(is.na(x)); if (length(NAidx) > 0) x[NAidx] <- "#FFFFFF"
98 ## convert to HCL coordinates
99 if(is.character(x)) {
100 HCL <- hex2RGB(x)
101 } else {
102 HCL <- x
103 x <- hex(x)
104 }
105 HCL <- coords(as(HCL, "polarLUV"))[, c("H", "C", "L")]
106 n <- nrow(HCL)
107
108 ## determine type of palette based on luminance trajectory
109 lran <- diff(range(HCL[, "L"], na.rm = TRUE))
110 llin <- cor(HCL[, "L"], 1L:n, use = "pairwise.complete.obs")^2
111 ltri <- cor(HCL[, "L"], abs(1L:n - (n + 1)/2), use = "pairwise.complete.obs")^2
112 if(is.null(type)) {
113 type <- if(ltri > 0.75 & lran > 10) {
114 "diverging"
115 } else if(llin > 0.75 & lran > 10) {
116 "sequential"
117 } else {
118 "qualitative"
119 }
120 } else {
121 type <- match.arg(type, c("diverging", "sequential", "qualitative"))
122 }
123
124 ## FIXME: put into separate function
125 if(n > 1L) {
126 for(i in 2L:n) {
127 if ( any(is.na(HCL[(i-1L):i,])) ) next
128 d <- HCL[i, "H"] - HCL[i - 1L, "H"]
129 if (abs(d) > 320) HCL[i, "H"] <- HCL[i, "H"] - sign(d) * 360
130 if (abs(HCL[i, "H"]) > 360) HCL[1L:i, "H"] <- HCL[1L:i, "H"] - sign(HCL[i, "H"]) * 360
131 }
132
133 # (2) Smoothing hue values in batches where chroma is very low
134 idx <- which(HCL[, "C"] < 8)
135 if (length(idx) == n) {
136 HCL[,"H"] <- mean(HCL[,"H"])
137 } else if (length(idx) > 0L) {
138 ## pre-smooth hue
139 if(n >= 49L) {
140 HCL[, "H"] <- 1/3 * (
141 HCL[c(rep.int(1L, 2L), 1L:(n - 2L)), "H"] +
142 HCL[c(rep.int(1L, 1L), 1L:(n - 1L)), "H"] +
143 HCL[ 1L:n, "H"])
144 }
145 idxs <- split(idx, cumsum(c(1, diff(idx)) > 1))
146 s <- 1L
147 while(length(idxs) > 0L) {
148 e <- if(s %in% idxs[[1L]]) {
149 if(length(idxs) > 1L) idxs[[2L]] - 1L else n
150 } else {
151 if(n %in% idxs[[1L]]) n else round(mean(range(idxs[[1L]])))
152 }
153 io <- split(s:e, s:e %in% idx)
154 if (length(io) == 2L & sum(!is.na(HCL[io[["FALSE"]],"H"])) > 0) {
155 HCL[io[["TRUE"]], "H"] <- stats::spline(io[["FALSE"]], HCL[io[["FALSE"]], "H"],
156 xout = io[["TRUE"]], method = "natural")$y
157 }
158 idxs[[1L]] <- NULL
159 s <- e + 1L
160 }
161 }
162 }
163
164 maxchroma <- if(!is.null(c)) ceiling(c) else pmax(100, pmin(180, ceiling(max(HCL[, "C"], na.rm = TRUE)/20) * 20))
165
166 switch(type,
167 "sequential" = {
168 opar <- par(cex = cex, mar = c(3, 3, 2, 1) * cex, no.readonly = TRUE)
169 on.exit(par(opar))
170 nd <- expand.grid(C = 0:maxchroma, L = 0:100)
171 if(!is.null(h)) {
172 nd$H <- h
173 } else if(n < 3L || diff(range(HCL[, "H"], na.rm = TRUE)) < 12) {
174 nd$H <- median(HCL[, "H"], na.rm = TRUE)
175 } else {
176 m <- lm(H ~ C + L, data = as.data.frame(HCL))
177 sig <- summary(m)$sigma
178 if(is.na(sig) || sig > 7.5) warning("cannot approximate H well as a linear function of C and L")
179 nd$H <- predict(m, nd)
180 }
181
182 # Converting colors to HCL (no fixup), remove low-luminance colors
183 HCL2 <- hex(polarLUV(H = nd$H, C = nd$C, L = nd$L), fixup = FALSE)
184 HCL2[nd$L < 1 & nd$C > 0] <- NA
185
186 # Auto-generate main title
187 if(is.null(main)) {
188 # Reducing 'nd' to valid colors (!is.na(HCL2))
189 tmp <- nd[!is.na(HCL2), ]; tmp$H <- round(tmp$H)
190 main <- if (length(unique(tmp$H)) <= 1L) {
191 tmp$H[1L]
192 } else {
193 paste("[", min(tmp$H, na.rm = TRUE), ", ", max(tmp$H, na.rm = TRUE), "]", sep = "")
194 }
195 main <- paste("Hue =", main)
196 rm(tmp)
197 }
198
199 plot(0, 0, type = "n", xlim = c(0, maxchroma), ylim = c(0, 100), xaxs = "i", yaxs = "i",
200 xlab = NA, ylab = NA, main = main, axes = axes)
201 # Adding axis labels
202 if(axes) {
203 if ( is.null(xlab) ) xlab <- "Chroma"
204 if ( is.null(ylab) ) ylab <- "Luminance"
205 mtext(side = 1, line = 2 * cex, xlab, cex = cex)
206 mtext(side = 2, line = 2 * cex, ylab, cex = cex)
207 }
208 # Adding colors
209 points(nd$C, nd$L, col = HCL2, pch = 19, cex = 3)
210 points(HCL[, 2L:3L], pch = 19, cex = 1.1 * size * cex, type = "p", lwd = 5 * lwd, col = bg)
211 points(HCL[, 2L:3L], pch = 21, bg = x, cex = size * cex, type = "o", lwd = lwd)
212 box()
213 },
214 "diverging" = {
215 opar <- par(cex = cex, mar = c(3, 3, 2, 1) * cex, no.readonly = TRUE)
216 on.exit(par(opar))
217 nd <- expand.grid(C = -maxchroma:maxchroma, L = 0:100)
218 nd$H <- NA
219 nd$left <- nd$C < 0
220 left <- 1L:floor(n/2)
221 left <- left[HCL[left, "C"] > 10]
222 right <- (1 + ceiling(n/2)):n
223 right <- right[HCL[right, "C"] > 10]
224
225 if(!is.null(h)) {
226 if(length(h) == 2L) {
227 nd$H[nd$left] <- h[1L]
228 nd$H[!nd$left] <- h[2L]
229 } else {
230 nd$H <- h
231 }
232 } else if(n < 6L || (diff(range(HCL[left, "H"] - min(HCL[ left, "H"], na.rm = TRUE), na.rm = TRUE)) < 12 &
233 diff(range(HCL[right, "H"] - min(HCL[right, "H"], na.rm = TRUE), na.rm = TRUE)) < 12)) {
234 nd$H[nd$left] <- median(HCL[ left, "H"] - min(HCL[ left, "H"], na.rm = TRUE), na.rm = TRUE) + min(HCL[ left, "H"], na.rm = TRUE)
235 nd$H[!nd$left] <- median(HCL[right, "H"] - min(HCL[right, "H"], na.rm = TRUE), na.rm = TRUE) + min(HCL[right, "H"], na.rm = TRUE)
236 } else {
237 HCLdata <- as.data.frame(HCL)
238 HCLdata$left <- factor(rep(c(TRUE, FALSE), c(floor(n/2), ceiling(n/2))))
239 nd$left <- factor(nd$left)
240 m <- lm(H ~ left * (C + L), data = HCLdata)
241 sig <- summary(m)$sigma
242 if(is.na(sig) || sig > 7.5) warning("cannot approximate H well as a linear function of C and L")
243 nd$H <- predict(m, nd)
244 nd$left <- nd$left == "TRUE"
245 }
246
247 # Converting colors to HCL (no fixup), remove low-luminance colors
248 HCL2 <- hex(polarLUV(H = nd$H, C = abs(nd$C), L = nd$L), fixup = FALSE)
249 HCL2[nd$L < 1 & abs(nd$C) > 0] <- NA
250
251 # Auto-generate main title
252 if(is.null(main)) {
253 # Reducing 'nd' to valid colors (!is.na(HCL2))
254 tmp <- nd[!is.na(HCL2), ]; tmp$H <- round(tmp$H)
255 main <- if(length(unique(tmp$H)) <= 2L) {
256 paste(tmp$H[tmp$left][1L], "/", tmp$H[!tmp$left][1L])
257 } else {
258 paste("[", min(tmp$H[tmp$left], na.rm = TRUE), ", ", max(tmp$H[tmp$left], na.rm = TRUE), "] / [",
259 min(tmp$H[!tmp$left], na.rm = TRUE), ", ", max(tmp$H[!tmp$left], na.rm = TRUE), "]", sep = "")
260 }
261 main <- paste("Hue =", main)
262 rm(tmp)
263 }
264
265 plot(0, 0, type = "n", xlim = c(-1, 1) * maxchroma, ylim = c(0, 100), xaxs = "i", yaxs = "i",
266 xlab = NA, ylab = NA, main = main, axes = FALSE)
267 # Axis labels
268 if(axes) {
269 if ( is.null(xlab) ) xlab <- "Chroma"
270 if ( is.null(ylab) ) ylab <- "Luminance"
271 mtext(side = 1, line = 2 * cex, xlab, cex = cex)
272 mtext(side = 2, line = 2 * cex, ylab, cex = cex)
273 at1 <- pretty(c(-1, 1) * maxchroma)
274 axis(1, at = at1, labels = abs(at1))
275 axis(2)
276 }
277 # Plotting colors
278 points(nd$C, nd$L, col = HCL2, pch = 19, cex = 3)
279 points( HCL[, "C"] * ifelse(1L:n <= floor(mean(n/2)), -1, 1),
280 HCL[, "L"], pch = 19, cex = 1.1 * size * cex, type = "p", lwd = 5 * lwd, col = bg)
281 points( HCL[, "C"] * ifelse(1L:n <= floor(mean(n/2)),-1,1),
282 HCL[, "L"], pch = 21, bg = x, cex = size * cex, type = "o", lwd = lwd)
283 box()
284 },
285 "qualitative" = {
286 opar <- par(cex = cex, mar = c(1, 1, 2, 1) * cex, bty = "n", no.readonly = TRUE)
287 on.exit(par(opar))
288 nd <- expand.grid(H = 0:180 * 2, C = 0:maxchroma)
289
290 if(!is.null(l)) {
291 nd$L <- l
292 } else if(n < 3L || diff(range(HCL[, "L"], na.rm = TRUE)) < 10) {
293 nd$L <- median(HCL[, "L"], na.rm = TRUE)
294 } else {
295 m <- lm(L ~ C + H, data = as.data.frame(HCL))
296 sig <- summary(m)$sigma
297 if(is.na(sig) || sig > 7.5) warning("cannot approximate L well as a linear function of H and C")
298 nd$L <- predict(m, nd)
299 nd$L <- pmin(100, pmax(0, nd$L))
300 }
301
302 # Converting colors to HCL (no fixup), remove low-luminance colors
303 HCL2 <- hex(polarLUV(H = nd$H, C = nd$C, L = nd$L), fixup = FALSE)
304 HCL2[nd$L < 1 & nd$C > 0] <- NA
305
306 # Auto-generate main title
307 if(is.null(main)) {
308 # Reducing 'nd' to valid colors (!is.na(HCL2))
309 tmp <- nd[!is.na(HCL2), ]; tmp$L <- round(tmp$L)
310 main <- if (length(unique(tmp$L)) <= 1L) {
311 tmp$L[1L]
312 } else {
313 paste("[", min(tmp$L, na.rm = TRUE), ", ", max(tmp$L, na.rm = TRUE), "]", sep = "")
314 }
315 main <- paste("Luminance =", main)
316 rm(tmp)
317 }
318
319 # fact: used for scaling
320 fact <- 1.1 + (cex - 1) / 10
321 plot(0, 0, type = "n", axes = FALSE, xlab = NA, ylab = NA, main = main,
322 xlim = c(-maxchroma, maxchroma) * fact, ylim = c(-maxchroma, maxchroma) * fact, asp = 1)
323 xpos <- function(h, c) cos(h * pi/180) * c
324 ypos <- function(h, c) sin(h * pi/180) * c
325 points(xpos(nd$H, nd$C), ypos(nd$H, nd$C), col = HCL2, pch = 19, cex = 3)
326 lines(xpos(0:360, maxchroma), ypos(0:360, maxchroma))
327
328 if(axes) {
329 if(is.null(xlab)) xlab <- "Chroma"
330 if(is.null(ylab)) ylab <- "Hue"
331 at.c <- if(maxchroma >= 150) 0:3 * 50 else 0:3 * 25
332 at.h <- 0:6 * 60
333 lines(c(0, maxchroma), c(0, 0))
334 text(at.c, rep(-7, length(at.c)), at.c)
335 text(50, -14, xlab)
336 rect(at.c, 0, at.c, -3)
337 if(0 %in% at.h | 360 %in% at.h) {
338 lines(xpos(0, maxchroma + c(0, 3)), ypos(0, maxchroma + c(0, 3)))
339 text(xpos(0, maxchroma + 7), ypos(0, maxchroma + 7), 0, pos = 3)
340 text(xpos(0, maxchroma + 7), ypos(0, maxchroma + 7), 360, pos = 1)
341 text(xpos(0, maxchroma + 16), ypos(0, maxchroma + 16), ylab)
342 }
343 at.h <- at.h[at.h > 0 & at.h < 360]
344 for(hue in at.h) {
345 text(xpos(hue, maxchroma + 7), ypos(hue, maxchroma + 7), hue)
346 lines(xpos(hue, maxchroma + c(0, 3)), ypos(hue, maxchroma + c(0, 3)))
347 }
348 }
349 points(xpos(HCL[, "H"], HCL[, "C"]), ypos(HCL[, "H"], HCL[, "C"]),
350 pch = 19, cex = 1.1 * size * cex, type = "p", lwd = 5 * lwd, col = bg)
351 points(xpos(HCL[, "H"], HCL[, "C"]), ypos(HCL[, "H"], HCL[, "C"]),
352 pch = 21, bg = x, cex = size * cex, type = "o", lwd = lwd)
353 box()
354 }
355 )
356
357 invisible(HCL)
358 }