--- title: "Color recipes" author: "SPDS, uni.kn" date: "2022 11 30" output: rmarkdown::html_vignette: fig_caption: yes vignette: > %\VignetteIndexEntry{Color recipes} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r setup, include = FALSE} options(max.print = "75") knitr::opts_chunk$set(echo = TRUE, cache = FALSE, prompt = FALSE, tidy = FALSE, collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE, # Default figure options: # fig.width = 6, # fig.asp = .8 # .618, # golden ratio fig.align = "center", out.width = "60%") # URLs: ------ # unikn / Uni Konstanz: url_unikn <- "https://www.uni-konstanz.de" # unikn package: url_unikn_cran <- "https://CRAN.R-project.org/package=unikn" url_unikn_github <- "https://github.com/hneth/unikn" # unicol package: url_unicol_cran <- "https://CRAN.R-project.org/package=unicol" url_unicol_github <- "https://github.com/hneth/unicol" ``` This vignette shows how various color-related tasks can be solved by the tools provided by **unikn**. (For a general introduction of the **unikn** colors, color palettes, and color functions, see the vignette on [Colors and color functions](color_functions.html). The vignette on [text](text_decorations.html) provides information on creating text boxes and decorations.) The following recipes illustrate how plotting functions in R can use the colors and color palettes provided by the **unikn** package. Additional examples show how we can use the `seecol()`, `usecol()`, `newpal()`, and `grepal()` functions for solving color-related tasks. Please install and/or load the **unikn** package to get started: ```{r load-pkg-colors, message = FALSE, warning = FALSE} # install.packages('unikn') # install unikn from CRAN client library('unikn') # loads the package ``` ## Using colors in **base** R **Task:** Using **unikn** colors in visualizations created by **base** R graphics. When creating **base** R visualizations (e.g., using `plot()` for creating a scatterplot), use the `usecol()` function in combination with any color palette (e.g., `pal_unikn`) as the `col`\ argument: ```{r plot-par-set, echo = FALSE} opar <- par(no.readonly = TRUE) # store current settings par(mar = c(1, 1, 2.1, 1), oma = c(0, 0, 0, 0)) # reduce margins set.seed(6 * pi) # reproducible randomness ``` ```{r demo-scatterplot, eval = TRUE, fig.width = 5, fig.asp=.95, fig.align = 'center', collapse = TRUE} my_col <- usecol(pal_unikn, alpha = .50) # with transparency plot(x = runif(99), y = runif(99), type = "p", pch = 16, cex = 4, col = my_col, main = "99 transparent dots", axes = FALSE, xlab = NA, ylab = NA) ``` ```{r plot-par-reset, echo = FALSE} par(opar) # re-store current settings ``` ## Using colors in **ggplot2** **Task:** Using **unikn** colors in visualizations created by the **ggplot2** package. When using the `ggplot()` function of **ggplot2** (e.g., for creating an area plot), use the `usecol()` function for defining a color palette (of the desired length and transparency) that is then provided as the `values` of the `scale_color_manual()` or `scale_fill_manual()` functions: 1. Wrap the desired color palette in the `usecol()` function of **unikn**. 2. Provide this palette as the `values` of the **ggplot2** functions `scale_color_manual()` or `scale_fill_manual()`. ```{r use-pal-ggplot2, eval = FALSE, fig.width = 6, fig.asp = .618, fig.align = 'center', collapse = TRUE} # 0. Create data: ---- # Example based on https://www.r-graph-gallery.com/137-spring-shapes-data-art/ n <- 50 groups <- 1:n df <- data.frame() set.seed(3) for (i in seq(1:30)){ data = data.frame(matrix(0, n, 3)) data[, 1] <- i data[, 2] <- sample(groups, nrow(data)) data[, 3] <- prop.table(sample(c(rep(0, 100), c(1:n)), nrow(data))) df = rbind(df, data)} names(df) <- c("X","Group","Y") df$Group <- as.factor(df$Group) df <- df[c(2, 1, 3)] df <- df[order(df$X, df$Group) , ] rownames(df) <- NULL my_data <- df # 1. Colors: ---- # A. using RColorBrewer: # library(RColorBrewer) # cur_col <- brewer.pal(11, "Paired") # cur_col <- colorRampPalette(cur_col)(n) # cur_col <- cur_col[sample(c(1:length(cur_col)), size = length(cur_col))] # randomize # B. using unikn colors: library(unikn) # Mix a color gradient: cur_col <- usecol(c(Bordeaux, "white", Petrol), n = n) # cur_col <- cur_col[sample(c(1:length(cur_col)), size = length(cur_col))] # randomize # 2. Plotting: ---- library(ggplot2) ggplot(my_data, aes(x = X, y = Y, fill = Group)) + geom_area() + scale_fill_manual(values = cur_col) + theme_void() + theme(legend.position = "none") ```
## Viewing and comparing color palettes **Task:** Inspect (the colors and details of) a color palette. For easily viewing an individual color palette (e.g., provided by the new HCL color palettes `hcl.pals()` of\ R), use the palette as the `pal`\ argument of the `seecol()` function: ```{r seecol-example-1, fig.width = 5, fig.asp = .80, fig.align = 'center'} col_pal <- hcl.colors(10, "Vik") # some color palette seecol(col_pal) # see its colors and details ``` Note that the other arguments of the `seecol()` function ---\ especially `n` and `alpha`\ --- can modify the palette (in the same ways as the `usecol()` function). **Task:** Compare (the colors and range of) multiple color palettes. For comparing multiple color palettes (e.g., 20\ random color palettes of `hcl.pals()`), provide them as a list in the `pal`\ argument of the `seecol()`\ function. For instance, let's create and compare a set of 20\ random HCL palettes: ```{r set-seed-HCL-pals, echo = FALSE} set.seed(4 * pi) # reproducible randomenss ``` - Generate random HCL\ palettes (and save them as a list): ```{r seecol-example-2a, fig.width = 6, fig.asp = 1.0, fig.align = 'center'} # Parameters: n_col <- 8 # colors in each palette n_pal <- 20 # length(hcl.pals()) ptype <- NULL # c("diverging", "divergingx", "qualitative", "sequential")[4] s_pal <- sample(x = hcl.pals(type = ptype), size = n_pal, replace = FALSE) s_pal <- sort(s_pal) # Initialize: t_lbl <- paste0("See ", n_pal, " random HCL color palettes (n = ", n_col, ")") l_pal <- vector("list", n_pal) # lists of palettes # Loop: for (i in 1:n_pal){ l_pal[[i]] <- hcl.colors(n = n_col, palette = s_pal[i]) } ``` - Use `seecol()` for comparing multiple color palettes: ```{r seecol-example-2b, fig.width = 6, fig.asp = 1.0, fig.align = 'center'} seecol(pal = l_pal, pal_names = s_pal, col_brd = "white", lwd_brd = 1, main = t_lbl) ``` ## Finding similar colors **Task:** Find a color that is similar to some given color. Use the `simcol()` function for finding (and plotting/seeing) similar colors: ```{r simcol-example-01, fig.width = 5, fig.asp = .90, fig.align = 'center', fig.show = "hold"} simcol("forestgreen") ``` The `simcol()` function compares a require target color (`col_target`) with a set of candidate colors (`col_candidates`, set to `colors()` by default). Color similarity is defined in terms of the colors' pair-wise distances in RGB values. If this distance falls below some tolerance value(s) (`tol`), the corresponding `col_candidates` are shown and returned. Thus, increasing the tolerance value yields a wider range of colors: ```{r simcol-example-02, fig.width = 5, fig.asp = .90, fig.align = 'center', fig.show = "hold"} simcol(col_target = "orange", col_candidates = pal_unikn_pref, tol = 150) ``` Specifying a vector of three `tol` values compares RGB dimensions in the order of their rank. This allows for more fine-grained similarity searches: ```{r simcol-example-03, fig.width = 5, fig.asp = .90, fig.align = 'center', fig.show = "hold"} simcol(col_target = Seeblau, tol = c(20, 20, 80)) ``` ## Creating new color palettes **Task:** Create a new color palette (with color names). The general steps for creating an new color palette (with dedicated color names) are: 1. Choose some colors (and their R color names, or as RGB/HEX/HCL values, e.g., from sites like