| 1 |
#' Color Spectrum Plot |
| 2 |
#' |
| 3 |
#' Visualization of color palettes (given as hex codes) in HCL and/or RGB |
| 4 |
#' coordinates. |
| 5 |
#' |
| 6 |
#' The function \code{specplot} transforms a given color palette in hex codes |
| 7 |
#' into their HCL (\code{\link[colorspace]{polarLUV}}) and/or RGB |
| 8 |
#' (\code{\link[colorspace]{sRGB}}) coordinates. As the hues for low-chroma |
| 9 |
#' colors are not (or poorly) identified, by default a smoothing is applied to |
| 10 |
#' the hues (\code{fix = TRUE}). Also, to avoid jumps from 0 to 360 or vice |
| 11 |
#' versa, the hue coordinates are shifted suitably. |
| 12 |
#' |
| 13 |
#' By default (\code{plot = TRUE}), the resulting HCL and optionally RGB coordinates are |
| 14 |
#' visualized by simple line plots along with the color palette \code{x} |
| 15 |
#' itself. The x-axis simply gives the ordering of the colors in the palette |
| 16 |
#' The y-axis depicts the following information: (1) Hue is drawn in red and |
| 17 |
#' coordinates are indicated on the axis on the right with range [0, 360] or |
| 18 |
#' (if necessary) [-360, 360]. (2) Chroma is drawn in green with coordinates on |
| 19 |
#' the left axis. The range [0, 100] is used unless the palette necessitates |
| 20 |
#' higher chroma values. (3) Luminance is drawn in blue with coordinates on the |
| 21 |
#' left axis in the range [0, 100]. Luminance (and hence also chroma) is on |
| 22 |
#' the left axis because it is arguably most important for understanding the |
| 23 |
#' type of palette (qualitative vs. sequential vs. diverging). To facilitate |
| 24 |
#' reading the legend the reversed order Luminance / Chroma / Hue is used so that |
| 25 |
#' the legend labels are closer to the axis they pertain to. |
| 26 |
#' |
| 27 |
#' For comparing two palettes, \code{specplot(x, y)} can be used which adds |
| 28 |
#' lines (dashed, by default) corresponding to the \code{y} palette HCL/RGB |
| 29 |
#' coordinates in the display. |
| 30 |
#' |
| 31 |
#' @param x character vector containing color hex codes. |
| 32 |
#' @param y optional second character vector containing further color hex codes, |
| 33 |
#' to be used for comparing two palettes (\code{x} vs. \code{y}). |
| 34 |
#' @param rgb logical or color specification. Should the RGB spectrum be |
| 35 |
#' visualized? Can also be a vector of three colors for the legend of R/G/B coordinates. |
| 36 |
#' @param hcl logical or color specification. Should the HCL spectrum be |
| 37 |
#' visualized? Can also be a vector of three colors for the legend of H/C/L coordinates. |
| 38 |
#' @param fix logical. Should the hues be fixed to be on a smooth(er) curve? |
| 39 |
#' For details see below. |
| 40 |
#' @param cex numeric. Character extension for figure axes and labels. |
| 41 |
#' @param type,lwd,lty,pch plotting parameters passed to |
| 42 |
#' \code{\link[graphics]{lines}} for drawing the RGB and HCL coordinates, |
| 43 |
#' respectively. Can be vectors of length 3. |
| 44 |
#' @param mar,oma numeric or logical. Either numeric vectors of length 4 giving |
| 45 |
#' the (outer) margins or a logical indicating whether \code{mar}/\code{oma} |
| 46 |
#' should be set. |
| 47 |
#' @param main character. Main title of the plot. |
| 48 |
#' @param legend logical. Should legends for the coordinates be plotted? |
| 49 |
#' @param palette logical. Should the given palette \code{x} be plotted? |
| 50 |
#' @param plot logical. Should the RGB and/or HCL coordinates be plotted? |
| 51 |
#' @param \dots currently not used. |
| 52 |
#' @return \code{specplot} invisibly returns a list with components |
| 53 |
#' \item{HCL}{a matrix of HCL coordinates,} |
| 54 |
#' \item{RGB}{a matrix of sRGB coordinates,} |
| 55 |
#' \item{hex}{original color palette \code{x}.} |
| 56 |
#' @author Reto Stauffer, Achim Zeileis |
| 57 |
#' @seealso \code{\link{hcl_palettes}}, \code{\link{hclplot}} |
| 58 |
#' @references Zeileis A, Hornik K, Murrell P (2009). Escaping RGBland: |
| 59 |
#' Selecting Colors for Statistical Graphics. \emph{Computational Statistics & |
| 60 |
#' Data Analysis}, \bold{53}, 3259--3270. |
| 61 |
#' \doi{10.1016/j.csda.2008.11.033} |
| 62 |
#' Preprint available from |
| 63 |
#' \url{https://www.zeileis.org/papers/Zeileis+Hornik+Murrell-2009.pdf}. |
| 64 |
#' |
| 65 |
#' Stauffer R, Mayr GJ, Dabernig M, Zeileis A (2015). Somewhere over the |
| 66 |
#' Rainbow: How to Make Effective Use of Colors in Meteorological |
| 67 |
#' Visualizations. \emph{Bulletin of the American Meteorological Society}, |
| 68 |
#' \bold{96}(2), 203--216. |
| 69 |
#' \doi{10.1175/BAMS-D-13-00155.1} |
| 70 |
#' |
| 71 |
#' Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020). |
| 72 |
#' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.} |
| 73 |
#' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49. \doi{10.18637/jss.v096.i01} |
| 74 |
#' @keywords hplot |
| 75 |
#' @examples |
| 76 |
#' ## spectrum of the (in)famous RGB rainbow palette (in both RGB and HCL) |
| 77 |
#' specplot(rainbow(100), rgb = TRUE) |
| 78 |
#' |
| 79 |
#' ## spectrum of HCL-based palettes: qualitative/sequential/diverging |
| 80 |
#' specplot(qualitative_hcl(100, "Set 2")) |
| 81 |
#' specplot(sequential_hcl(100, "Blues 2")) |
| 82 |
#' specplot(diverging_hcl(100, "Blue-Red")) |
| 83 |
#' |
| 84 |
#' ## return computed RGB and HCL coordinates |
| 85 |
#' res <- specplot(rainbow(10), plot = FALSE) |
| 86 |
#' print(res) |
| 87 |
#' @export specplot |
| 88 |
#' @importFrom graphics axis image layout legend lines mtext text par plot |
| 89 |
#' @importFrom stats median sd |
| 90 |
specplot <- function(x, y = NULL, rgb = FALSE, hcl = TRUE, fix = TRUE, cex = 1, |
| 91 |
type = "l", lwd = 2 * cex, lty = 1, pch = NULL, mar = NULL, oma = NULL, |
| 92 |
main = NULL, legend = TRUE, palette = TRUE, plot = TRUE, ...) |
| 93 |
{ |
| 94 |
|
| 95 |
# Replace NA x with white, required for hex2RGB. |
| 96 |
# Store indizes of NA x to x.na for further |
| 97 |
# processing. |
| 98 |
x.na <- which(is.na(x)) |
| 99 |
if (length(x.na) > 0) x[x.na] <- "#ffffff" |
| 100 |
RGB <- hex2RGB(x) |
| 101 |
HCL <- as(RGB, "polarLUV") |
| 102 |
|
| 103 |
# Replace coordinates of NA x with NA |
| 104 |
RGB <- coords(RGB) |
| 105 |
HCL <- coords(HCL)[, c("H", "C", "L")] |
| 106 |
HCL[which(is.na(HCL), arr.ind = TRUE)] <- 0 |
| 107 |
if (length(x.na) > 0L) { |
| 108 |
for (i in 1:3) { |
| 109 |
HCL[x.na, i] <- NA |
| 110 |
RGB[x.na, i] <- NA |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
# Fixing hue paths |
| 115 |
if(fix & nrow(HCL) > 1L) { |
| 116 |
# (1) as(RGB, "polarLUV") returns hue's in the |
| 117 |
# range of 0-360. A palette from -100 to +100 results in |
| 118 |
# c(260-360,0,100) - the iterative approach corrects this. |
| 119 |
|
| 120 |
## strategy: |
| 121 |
## change H by +360 or -360 if the hue trajectory has a very large jump, |
| 122 |
## (i.e., difference > +/- 300) or if the trajectory is essentially linear |
| 123 |
## but has a jump by +360 or -360 in additional to the "usual" difference |
| 124 |
## (i.e., median difference +/- 360) |
| 125 |
md <- median(HCL[2L:nrow(HCL), "H"] - HCL[1L:(nrow(HCL) - 1L), "H"], na.rm = TRUE) |
| 126 |
for(i in 2L:nrow(HCL)) { |
| 127 |
if ( any(is.na(HCL[(i-1L):i,])) ) next |
| 128 |
d <- HCL[i, "H"] - HCL[i - 1L, "H"] |
| 129 |
if (abs(d) > 300 || (abs(d + 360 - md) < 4 || abs(d - 360 - md) < 4) ) 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 (ad hoc: < 8) |
| 134 |
idx <- which(HCL[, "C"] < 8) |
| 135 |
if (length(idx) == nrow(HCL)) { |
| 136 |
HCL[, "H"] <- mean(HCL[, "H"], na.rm = TRUE) |
| 137 |
} else if (length(idx) > 0L) { |
| 138 |
# (a) pre-fixing hues where luminance is < 2 | > 98 |
| 139 |
ix <- split(1:nrow(HCL), HCL[,"L"] < 2 | HCL[,"L"] > 98) |
| 140 |
if ( length(ix) == 2L ) { |
| 141 |
fun_fix_H <- function(HCL, ix, i) HCL[which.min(abs(ix["FALSE"][[1L]] - i)), "H"] |
| 142 |
HCL[ix["TRUE"][[1L]]] <- sapply(ix["TRUE"][[1L]], fun_fix_H, HCL = HCL, ix = ix) |
| 143 |
} |
| 144 |
## (b) pre-smooth hue by rolling mean of length 3 |
| 145 |
n <- nrow(HCL) |
| 146 |
if(n >= 49L) { |
| 147 |
HCL[, "H"] <- rowMeans(cbind( |
| 148 |
HCL[c(rep.int(1L, 2L), 1L:(n - 2L)), "H"], |
| 149 |
HCL[c(rep.int(1L, 1L), 1L:(n - 1L)), "H"], |
| 150 |
HCL[ 1L:n, "H"]), na.rm = TRUE) |
| 151 |
HCL[x.na, "H"] <- NA |
| 152 |
} |
| 153 |
## (c) interpolate linearly or by natural spline |
| 154 |
|
| 155 |
## index list of consecutive segments with low-chroma colors |
| 156 |
idxs <- split(idx, cumsum(c(1, diff(idx)) > 1)) |
| 157 |
|
| 158 |
## find start "s" and end "e" for each consecutive segment |
| 159 |
## (= problematic low-chroma indexes plus adjacent ok-chroma indexes) |
| 160 |
## distinguish: one vs. more problematic segments |
| 161 |
## and: problems only at beginning or end vs. in the middle (diverging) |
| 162 |
s <- 1L |
| 163 |
while(length(idxs) > 0L) { |
| 164 |
e <- if(any(s %in% idxs[[1L]])) { |
| 165 |
if(length(idxs) > 1L) idxs[[2L]] - 1L else n |
| 166 |
} else { |
| 167 |
if(n %in% idxs[[1L]]) n else round(mean(range(idxs[[1L]]))) |
| 168 |
} |
| 169 |
## "in" vs. "out" of low-chroma in current segment |
| 170 |
io <- split(min(s):max(e), (min(s):max(e) %in% idx) | (min(s):max(e) %in% x.na)) |
| 171 |
|
| 172 |
## given enough ok-chroma observations fit a curve |
| 173 |
## - either linear if residual standard error is small enough |
| 174 |
## - or natural spline |
| 175 |
if (length(io) == 2L & sum(!is.na(HCL[io[["FALSE"]], "H"])) > 0 & length(io[["FALSE"]]) > 1) { |
| 176 |
linfit <- stats::lm.fit(cbind(1, io[["FALSE"]]), HCL[io[["FALSE"]], "H"]) |
| 177 |
HCL[io[["TRUE"]], "H"] <- if(sd(linfit$residuals) < 1.3) { |
| 178 |
drop(cbind(1, io[["TRUE"]]) %*% linfit$coefficients) |
| 179 |
} else { |
| 180 |
stats::spline(io[["FALSE"]], HCL[io[["FALSE"]], "H"], |
| 181 |
xout = io[["TRUE"]], method = "natural")$y |
| 182 |
} |
| 183 |
HCL[x.na, "H"] <- NA |
| 184 |
} |
| 185 |
idxs[[1L]] <- NULL |
| 186 |
s <- e + 1L |
| 187 |
} |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
# plot spectra and palette? |
| 192 |
if(isTRUE(rgb)) rgb <- hex(sRGB(c(0.8, 0, 0), c(0, 0.8, 0), c(0, 0, 0.8))) |
| 193 |
if(isTRUE(hcl)) hcl <- qualitative_hcl(3L) |
| 194 |
show_rgb <- !identical(rgb, FALSE) |
| 195 |
show_hcl <- !identical(hcl, FALSE) |
| 196 |
|
| 197 |
if(plot & (length(x.na) == length(x))) { |
| 198 |
opar <- par(no.readonly = TRUE) |
| 199 |
nam <- names(par(xaxt = "n", yaxt = "n", bty = "n", mar = rep(0, 4))) |
| 200 |
on.exit(par(opar[nam])) |
| 201 |
|
| 202 |
plot(0, type = "n", xlim = c(-1, 1), ylim = c(-1, 1)) |
| 203 |
text(0, 0, "All colors NA\nCannot draw spectrum", col = 2) |
| 204 |
} else if(plot) { |
| 205 |
## add second palette as a reference? |
| 206 |
if(!is.null(y)) { |
| 207 |
yspec <- specplot(y, rgb = rgb, hcl = hcl, fix = fix, plot = FALSE) |
| 208 |
y <- TRUE |
| 209 |
} else { |
| 210 |
yspec <- NULL |
| 211 |
y <- FALSE |
| 212 |
} |
| 213 |
|
| 214 |
## set up graphical parameters and plot layout |
| 215 |
nr <- show_rgb + palette + (palette && y) + show_hcl |
| 216 |
opar <- par(no.readonly = TRUE) |
| 217 |
if(identical(mar, FALSE)) opar$mar <- NULL |
| 218 |
if(identical(oma, FALSE)) opar$oma <- NULL |
| 219 |
if(nr < 2L) opar$mfrow <- opar$mfcol <- opar$mfg <- NULL |
| 220 |
on.exit(par(opar)) |
| 221 |
if(nr > 1L) { |
| 222 |
layout(matrix(1L:nr, ncol = 1L, nrow = nr), |
| 223 |
heights = c(if(show_rgb) 10 else NULL, if(palette) 2 else NULL, if(palette && y) 2 else NULL, if(show_hcl) 10 else NULL)) |
| 224 |
} |
| 225 |
par(xaxt = "n", xaxs = "i", yaxs = "i", cex = cex) |
| 226 |
if(!identical(mar, FALSE)) { |
| 227 |
if(is.null(mar) || isTRUE(mar)) mar <- c(0.2, 0, 0.2, 0) |
| 228 |
par(mar = mar) |
| 229 |
} |
| 230 |
if(!identical(oma, FALSE)) { |
| 231 |
if(is.null(oma) || isTRUE(oma)) oma <- c(2, 3, 2 + !is.null(main), 3) |
| 232 |
par(oma = oma) |
| 233 |
} |
| 234 |
|
| 235 |
## expand plotting parameters |
| 236 |
rgb <- rep(rgb, length.out = 3L) |
| 237 |
hcl <- rep(hcl, length.out = 3L) |
| 238 |
lwd <- rep(lwd, length.out = 3L) |
| 239 |
lty <- rep(lty, length.out = 3L) |
| 240 |
type<- rep(type,length.out = 3L) |
| 241 |
pch <- if(is.null(pch)) ifelse(type == "l", NA, 1) else rep(pch, length.out = 3L) |
| 242 |
|
| 243 |
# RGB spectrum |
| 244 |
if(show_rgb) { |
| 245 |
plot(0, type = "n", ylim = c(0, 1), xlim = c(1, length(x))) |
| 246 |
lines(RGB[, "R"], lwd = lwd[1L], lty = lty[1L], col = rgb[1L], type = type[1L], pch = pch[1L]) |
| 247 |
lines(RGB[, "G"], lwd = lwd[2L], lty = lty[2L], col = rgb[2L], type = type[1L], pch = pch[1L]) |
| 248 |
lines(RGB[, "B"], lwd = lwd[3L], lty = lty[3L], col = rgb[3L], type = type[1L], pch = pch[1L]) |
| 249 |
if(y) { |
| 250 |
lines(yspec$RGB[, "R"], lwd = lwd[1L], lty = lty[1L] + 1L, col = rgb[1L], type = type[1L], pch = pch[1L]) |
| 251 |
lines(yspec$RGB[, "G"], lwd = lwd[2L], lty = lty[2L] + 1L, col = rgb[2L], type = type[1L], pch = pch[1L]) |
| 252 |
lines(yspec$RGB[, "B"], lwd = lwd[3L], lty = lty[3L] + 1L, col = rgb[3L], type = type[1L], pch = pch[1L]) |
| 253 |
} |
| 254 |
if(legend) legend("topleft", legend = c("Red", "Green", "Blue"), |
| 255 |
ncol = 3L, bty = "n", lwd = lwd, lty = lty, col = rgb, pch = pch) |
| 256 |
mtext(side = 3, "RGB Spectrum", cex = cex, line = 0.2) |
| 257 |
mtext(side = 2, "Red / Green / Blue", cex = cex, line = 2.0) |
| 258 |
if(!is.null(main)) { |
| 259 |
mtext(side = 3, main, line = 1.5, cex = 1.5 * cex) |
| 260 |
main <- NULL |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
# color palette |
| 265 |
if(palette) { |
| 266 |
par(xaxt = "n", yaxt = "n") |
| 267 |
image(matrix(seq_along(x), ncol = 1L), col = x) |
| 268 |
par(yaxt = "s") |
| 269 |
if(!is.null(main)) { |
| 270 |
mtext(side = 3, main, line = 1.0, cex = 1.5 * cex) |
| 271 |
main <- NULL |
| 272 |
} |
| 273 |
} |
| 274 |
if(palette && y) { |
| 275 |
par(xaxt = "n", yaxt = "n") |
| 276 |
image(matrix(seq_along(yspec$hex), ncol = 1L), col = yspec$hex) |
| 277 |
par(yaxt = "s") |
| 278 |
} |
| 279 |
|
| 280 |
# HCL spectrum |
| 281 |
if(show_hcl) { |
| 282 |
ymax <- pmax(max(HCL[, "C"], na.rm = TRUE) * 1.005, 100) |
| 283 |
yrad <- 360/ymax |
| 284 |
plot(0, type = "n", ylim = c(0, ymax), xlim = c(1, length(x))) |
| 285 |
if ( min(HCL[,"H"], na.rm = TRUE) >= -1 ) { |
| 286 |
labels <- seq( 0, 360, length.out = 5) |
| 287 |
axis(side = 4, at = labels/yrad, labels = labels) |
| 288 |
lines((HCL[, "H"])/yrad, lwd = lwd[1L], lty = lty[1L], col = hcl[1L], type = type[1L], pch = pch[1L]) |
| 289 |
if(y) lines((yspec$HCL[, "H"])/yrad, lwd = lwd[1L], lty = lty[1L] + 1L, col = hcl[1L], type = type[1L], pch = pch[1L]) |
| 290 |
} else { |
| 291 |
labels <- seq(-360, 360, length.out = 5) |
| 292 |
axis(side = 4, at = labels/(2 * yrad) + ymax/2, labels = labels) |
| 293 |
lines((HCL[, "H"] + 360)/(2 * yrad), lwd = lwd[1L], lty = lty[1L], col = hcl[1L], type = type[1L], pch = pch[1L]) |
| 294 |
if(y) lines((yspec$HCL[, "H"] + 360)/(2 * yrad), lwd = lwd[1L], lty = lty[1L] + 1L, col = hcl[1L], type = type[1L], pch = pch[1L]) |
| 295 |
} |
| 296 |
lines(HCL[, "C"], lwd = lwd[2L], lty = lty[2L], col = hcl[2L], type = type[1L], pch = pch[1L]) |
| 297 |
lines(HCL[, "L"], lwd = lwd[3L], lty = lty[3L], col = hcl[3L], type = type[1L], pch = pch[1L]) |
| 298 |
if(y) { |
| 299 |
lines(yspec$HCL[, "C"], lwd = lwd[2L], lty = lty[2L] + 1L, col = hcl[2L], type = type[1L], pch = pch[1L]) |
| 300 |
lines(yspec$HCL[, "L"], lwd = lwd[3L], lty = lty[3L] + 1L, col = hcl[3L], type = type[1L], pch = pch[1L]) |
| 301 |
} |
| 302 |
legend("bottomleft", legend = rev(c("Hue", "Chroma", "Luminance")), |
| 303 |
ncol = 3L, bty = "n", lwd = rev(lwd), lty = rev(lty), col = rev(hcl), pch = rev(pch)) |
| 304 |
mtext(side = 1, "HCL Spectrum", cex = cex, line = 0.2) |
| 305 |
mtext(side = 2, "Luminance / Chroma", cex = cex, line = 2.0) |
| 306 |
mtext(side = 4, "Hue", cex = cex, line = 2.0) |
| 307 |
if(!is.null(main)) mtext(side = 3, main, line = 1.0, cex = 1.5 * cex) |
| 308 |
} |
| 309 |
|
| 310 |
} |
| 311 |
|
| 312 |
# Return |
| 313 |
if ( length(x.na) > 0 ) x[x.na] <- NA |
| 314 |
invisible(list( |
| 315 |
HCL = HCL, |
| 316 |
RGB = RGB, |
| 317 |
hex = x) |
| 318 |
) |
| 319 |
} |