Debian Codegraph @

R/swatchplot.R

raw
1 #' Palette Swatch Plot
2 #'
3 #' Visualization of color palettes in columns of color swatches.
4 #'
5 #' The function \code{swatchplot} is a convenience function for displaying
6 #' collections of palettes that can be specified as lists or matrices of
7 #' character color specifications. Essentially, the function just calls
8 #' \code{\link[graphics]{rect}} but the value-added are the heuristics used
9 #' for choosing default labels, margins, spacings, borders. These are selected
10 #' to work well for \code{\link{hcl_palettes}} and might need further tweaking
11 #' in future versions.
12 #'
13 #' @param x character vector/matrix (or list of character vectors/matrices)
14 #' containing color hex codes.
15 #' @param \dots further (possibly named) character vectors/matrices with color
16 #' hex codes.
17 #' @param nrow integer specifying the maximal number of rows of swatches.
18 #' (The actual number might be lower in order to balance the rows used in each column.)
19 #' @param border color for border of individual color rectangles. By default
20 #' \code{"lightgray"} for up to 9 colors, \code{"transparent"} otherwise.
21 #' @param sborder color for border of the entire palette swatch. By default
22 #' \code{"lightgray"} if \code{border} is \code{"transparent"} and \code{"lightgray"}
23 #' otherwise (if \code{off = 0}).
24 #' @param off numeric vector of length 2. Offset in horizontal and vertical direction
25 #' (specified as a fraction of the rectangle for one color). By default, the
26 #' horizontal offset is \code{0.3} for up to 5 colors and \code{0} otherwise,
27 #' and the vertical offset is \code{0.1}.
28 #' @param mar numeric vector of length 4, specifying the margins of column
29 #' of color swatches.
30 #' @param line numeric. Line in which the palette names (if any) are printed
31 #' in the margin.
32 #' @param cex,font numeric vectors of length 1 or 2. Specifications for the
33 #' annotation text for the individual palettes and lists of palettes, respectively.
34 #' @param cvd logical or character indicating whether color vision deficiencies
35 #' should be emulated with \code{\link{desaturate}}, \code{\link{deutan}},
36 #' \code{\link{protan}}, \code{\link{tritan}}.
37 #' @return \code{swatchplot} invisibly returns a matrix with colors and annotations.
38 #' @references Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020).
39 #' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.}
40 #' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49. \doi{10.18637/jss.v096.i01}
41 #' @keywords hplot
42 #' @examples
43 #' ## swatches of several palette vectors
44 #' swatchplot(
45 #' "Hue" = sequential_hcl(5, h = c(0, 300), c = c(60, 60), l = 65),
46 #' "Chroma" = sequential_hcl(5, h = 0, c = c(100, 0), l = 65, rev = TRUE, power = 1),
47 #' "Luminance" = sequential_hcl(5, h = 260, c = c(25, 25), l = c(25, 90), rev = TRUE, power = 1),
48 #' off = 0
49 #' )
50 #'
51 #' ## swatches of named palette matrices
52 #' bprg <- c("Blues", "Purples", "Reds", "Greens")
53 #' swatchplot(
54 #' "Single-hue" = t(sapply(paste(bprg, 2), sequential_hcl, n = 7)),
55 #' "Single-hue (advanced)" = t(sapply(paste(bprg, 3), sequential_hcl, n = 7)),
56 #' "Multi-hue (advanced)" = t(sapply(bprg, sequential_hcl, n = 7)),
57 #' nrow = 5
58 #' )
59 #'
60 #' ## swatches with color vision deficiency emulation
61 #' swatchplot(sequential_hcl(7, "Viridis"), cvd = TRUE)
62 #' swatchplot(
63 #' "YlGnBu" = sequential_hcl(7, "YlGnBu"),
64 #' "Viridis" = sequential_hcl(7, "Viridis"),
65 #' cvd = c("deutan", "desaturate")
66 #' )
67 #' @export swatchplot
68 #' @importFrom graphics rect mtext par plot
69 swatchplot <- function(x, ..., nrow = 20, border = NULL, sborder = NULL, off = NULL,
70 mar = NULL, line = NULL, cex = NULL, font = 1:2, cvd = FALSE)
71 {
72 ## canonicalize specification to list of vectors/matrices
73 x <- if(missing(x)) {
74 list()
75 } else if(is.data.frame(x)) {
76 list(as.matrix(x))
77 } else if(is.matrix(x)) {
78 list(x)
79 } else if(!is.list(x)) {
80 list(x)
81 } else {
82 x
83 }
84 if(!missing(...)) {
85 x <- c(x, list(...))
86 }
87
88 if(!identical(cvd, FALSE)) {
89 if(identical(cvd, TRUE)) cvd <- c("deutan", "protan", "tritan", "desaturate")
90 for(i in seq_along(cvd)) {
91 cvd[i] <- match.arg(tolower(cvd[i]), c("deutan", "deuteranope", "protanope", "tritanope", "desaturated"))
92 if(cvd[i] == "deutan") cvd[i] <- "deuteranope"
93 }
94 substr(cvd, 1L, 1L) <- toupper(substr(cvd, 1L, 1L))
95 cvd <- c("Original", cvd)
96 cvd_trafo <- function(y) {
97 y <- as.character(y)
98 y <- rbind(
99 "Original" = y,
100 "Deuteranope" = deutan(y),
101 "Protanope" = protan(y),
102 "Tritanope" = tritan(y),
103 "Desaturated" = desaturate(y)
104 )
105 y <- y[cvd, , drop = FALSE]
106 }
107 x <- lapply(x, cvd_trafo)
108 }
109
110 ## expand to maximum number of palettes
111 n <- max(sapply(x, function(y) {
112 if(is.null(dim(y))) length(y) else ncol(y)
113 }))
114 x <- lapply(x, function(y) {
115 if(!is.character(y)) y[] <- as.character(y)
116 if(is.null(dim(y))) y <- matrix(y, ncol = length(y))
117 if(NCOL(y) < n) {
118 y <- cbind(y, matrix("transparent", nrow = NROW(y), ncol = n - NCOL(y)))
119 }
120 if(is.null(rownames(y))) rownames(y) <- rep.int("", NROW(y))
121 colnames(y) <- paste("Color", 1L:n)
122 return(y)
123 })
124 ## add extra row for names (if any)
125 if(!is.null(names(x))) {
126 x <- lapply(names(x), function(i) {
127 if(nrow(x[[i]]) == 1L && rownames(x[[i]]) == "") {
128 rownames(x[[i]]) <- i
129 return(x[[i]])
130 } else {
131 rbind(
132 matrix(rep.int("transparent", n), nrow = 1L, ncol = n,
133 dimnames = list(i, colnames(x[[i]]))),
134 x[[i]]
135 )
136 }
137 })
138 }
139
140 ## transform into one big matrix
141 x <- do.call("rbind", x)
142 x[is.na(x)] <- "transparent"
143 m <- nrow(x)
144
145 ## graphical parameters
146 rnam <- rownames(x)[x[,1L] != "transparent"]
147
148 if(is.null(cex)) cex <- if(m > 15L) 0.7 else 1
149 if(length(cex) < 2L) cex <- c(1, 1.4) * cex
150 mcex <- rep.int(cex[1L], m)
151 mcex[x[, 1L] == "transparent"] <- cex[2L]
152
153 mfont <- rep.int(font[1L], m)
154 mfont[x[, 1L] == "transparent"] <- font[2L]
155
156 lin <- if(is.null(line)) cex[1L] * (0.5 + max(nchar(rnam) - 1L)/2.25) else line
157 lin <- pmax(0.08, lin)
158
159 if(m > 1L) {
160 if(is.null(mar)) {
161 mar <- if(any(rnam != "")) {
162 c(0.1, 1.25 * lin, 0, 0)
163 } else {
164 c(0.1, 0.1, 0, 0)
165 }
166 }
167 nc <- ceiling(m/nrow)
168 nr <- ceiling(m/nc)
169 opar <- if(nc > 1L) par(mar = mar, mfrow = c(1L, nc)) else par(mar = mar)
170 on.exit(par(opar))
171 } else {
172 nc <- 1L
173 nr <- 1L
174 }
175 col <- rep_len(rep(1L:nc, each = nr), length.out = m)
176
177 if(is.null(off)) off <- if(n < 7L) 0.1 else 0
178 if(length(off) < 2L) off <- c(off, 0.3)
179 off <- c(1, 1) - off
180
181 ## swatch border color: light gray for sufficiently "discrete" case
182 if(is.null(border)) {
183 border <- if(n > 9L) "transparent" else "lightgray"
184 }
185 border <- rep.int(border, n * m)
186 border[x == "transparent"] <- "transparent"
187 border <- matrix(border, ncol = n)
188 ## palette border color: light gray for overall palette if off = 0 & border = "transparent"
189 if(is.null(sborder)) {
190 sborder <- ifelse(border[, 1L] == "transparent" & off[1L] >= 1, "lightgray", "transparent")
191 }
192 sborder <- rep.int(sborder, m)
193 sborder[apply(x == "transparent", 1, all)] <- "transparent"
194
195 ## visualization
196 for(i in 1L:nc) {
197 ## empty plot
198 plot(0, 0, type = "n", xlim = c(0, 1 - (1 - off[1L])/n), ylim = c(0, 1 - (1 - off[2L])/nr), axes = FALSE, xlab = "", ylab = "")
199 ## extract colors for i-th column
200 xi <- x[col == i, , drop = FALSE]
201 nri <- nrow(xi)
202 ## set up x- and y-coordinates for swatches
203 x1 <- rep(0:(n-1)/n, each = nri)
204 y1 <- rep.int((nr-1):(nr-nri)/nr, n)
205 ## annotation
206 mtext(rownames(xi), side = 2, at = y1[1L:nri] + 0.5 * off[2L]/nr,
207 las = 1, line = lin, adj = 0, cex = mcex[col == i], font = mfont[col == i])
208 ## draw swatches
209 rect(x1, y1, x1 + off[1L]/n, y1 + off[2L]/nr, col = xi, border = border[col == i])
210 ## draw palette borders
211 rect(0, y1[1L:nri], 1, y1[1L:nri] + off[2L]/nr, col = "transparent", border = sborder[(i - 1L) * nr + 1L:nri])
212 }
213
214 invisible(x)
215 }
216
217 ## ## Perceptually-based color model
218 ## ## Hue: Type of color (H = 0, ..., 300, C = 60, L = 65)
219 ## sequential_hcl(5, h = c(0, 300), c = c(60, 60), l = 65)
220 ## ## Chroma: Colorfulness (H = 0, C = 0, ..., 100, L = 65)
221 ## sequential_hcl(5, h = 0, c = c(100, 0), l = 65, rev = TRUE, power = 1)
222 ## ## Luminance: Brightness (H = 260, C = 25, L = 25, ..., 90)
223 ## sequential_hcl(5, h = 260, c = c(25, 25), l = c(25, 90), rev = TRUE, power = 1)