---
title: "Using color palettes"
author: "Hansjoerg Neth"
date: "`r Sys.Date()`"
output: 
  rmarkdown::html_vignette
vignette: > 
  %\VignetteIndexEntry{Using color palettes}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
org_opt <- options()  # store original user options

options(max.print = "75")

knitr::opts_chunk$set(collapse = FALSE, 
                      comment = "#>", 
                      prompt = FALSE,
                      tidy = FALSE,
                      echo = TRUE, 
                      message = FALSE,
                      warning = FALSE,
                      # Default figure options:
                      dpi = 100, 
                      fig.align = 'center',
                      fig.height = 5.0,
                      fig.width  = 7.5,
                      out.width = "600px")

# URLs: ------ 

# unicol package: 
url_unicol_cran   <- "https://CRAN.R-project.org/package=unicol"
url_unicol_github <- "https://github.com/hneth/unicol"

url_github_doc_rel <- "https://hneth.github.io/unicol/"      # release version  
url_github_doc_dev <- "https://hneth.github.io/unicol/dev/"  # dev version

# 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"
```

<!-- unikn logo and link: -->
<!-- <a href = "`r url_unikn`"> -->
<!-- <img src = "../man/figures/logo_unikn.png" alt = "unikn::" align = "right" width = "300px" style = "width: 300px; float: right; border:0;"/> -->
<!-- </a> -->

<!-- unikn pkg logo and link: -->
<!-- <a href = "`r url_unikn_cran`"> -->
<!-- <img src = "../man/figures/logo_unikn_pkg.png" alt = "unikn::" align = "right" width = "150px" style = "width: 150px; float: right; border:0;"/> -->
<!-- </a> -->

<!-- unicol pkg logo and link: -->
<a href = "`r url_unicol_cran`">
<img src = "../man/figures/logo.png" alt = "unicol::" align = "right" width = "150px" style = "width: 150px; float: right; border:0;"/>
</a>


This vignettes shows **how to** use the color palettes included in the **unicol** R\ package. 
(See the [All color palettes](color_pals.html) vignette for an overview of the palettes included in the package.) 

We install or load the **unicol** package to get started: 

```{r load-unicol-pkg, message = FALSE, warning = FALSE}
# install.packages('unicol')  # install unicol from CRAN client
library('unicol')             # load the package
```

Loading the **unicol** package automatically makes the color functions of the required **[unikn](`r url_unikn_cran`)** package available. 


## Using colors in **base** R 

**Task:** Using **unicol** colors in visualizations created by **base** R graphics. 

The **unicol** color palettes are typically provided as named vectors of color objects. 
Thus, when creating **base** R visualizations (e.g., using `plot()` for creating a scatterplot), we can directly use a color palette as the `col`\ argument. 

For instance, let's assume we wanted to create a bar chart using the color palette `uni_bonn_2` (of the [University of Bonn](https://www.uni-bonn.de), Germany): 

```{r plot-base-r-bonn-1}
# View color palette:
unikn::seecol(uni_bonn_2, main = "Color gradient of the University of Bonn, Germany")
```

We can simply provide the color palette to the `col` argument of the `barplot()` function:

```{r plot-base-r-bonn-2}
# Use a color palette:
barplot(1/sqrt(1:10), col = uni_bonn_2)
```


<!-- Example 2: Modify pal before using it in base R: -->

In case we want to modify a color palette (e.g., change its number of colors or add transparency) before using it, 
we can do so by using the `usecol()` function of the **[unikn](`r url_unikn_cran`)** package before providing the modified palette as the `col`\ argument of an R graphics function. 
The following examples illustrate both of these alternatives. 

```{r plot-base-r-caltech-1}
# View color palette:
unikn::seecol(caltech_1, main = "The colors of Caltech, USA")
```


```{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
```

1. Directly using a color palette (e.g., the color palette\ `caltech_1`): 

```{r demo-scatterplot-a, eval = TRUE, fig.width = 6, fig.asp = .90, out.width = "400px"}
plot(x = runif(99), y = runif(99), type = "p", 
     pch = 16, cex = 4,
     col = caltech_1,
     main = "99 dots (in Caltech colors)", axes = FALSE, xlab = NA, ylab = NA)
```

2. Using a transformed color palette (after using the `usecol()` function of the **[unikn](`r url_unikn_cran`)** package for resizing and adding transparency to the palette):

```{r demo-scatterplot-b, eval = TRUE, fig.width = 6, fig.asp = .90, out.width = "400px"}
my_col <- unikn::usecol(caltech_1, alpha = .60)  # 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 original user settings
```




## Using colors in **ggplot2**

**Task:** Using **unicol** colors in visualizations created by the **ggplot2** package.

When using the `ggplot()` function of **ggplot2** (e.g., for creating an area plot), 
we wrap the color palette in the `usecol()` function (of the **unikn** package) for defining a color palette (of the desired length and transparency). 
The resulting color palette can then be provided as the `values` of **ggplot2**'s `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 = TRUE, fig.width = 6, fig.asp = .65, out.width = "550px"}
# 0. Create some data to plot: ---- 

# Example based on https://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

# # View data (as wider table):
# my_data_wider <- tidyr::pivot_wider(my_data, names_from = Group, names_prefix = "g_", values_from = Y)
# knitr::kable(my_data_wider, caption = "Viewing data (in wider format).")


# 1. Colors: ---- 

# A. Using RColorBrewer: 
# library(RColorBrewer)

# my_pal <- brewer.pal(11, "Paired")
# my_pal <- colorRampPalette(my_pal)(n)
# my_pal <- my_pal[sample(c(1:length(my_pal)), size = length(my_pal))]  # randomize

# B. Using unicol colors:
library(unicol)

# Mix a color gradient: 
my_pal <- unikn::usecol(princeton_1, n = 50)
# my_pal <- my_pal[sample(c(1:length(my_pal)), size = length(my_pal))]  # randomize


# 2. Plotting (with ggplot2): ---- 

library(ggplot2)

ggplot2::ggplot(my_data, aes(x = X, y = Y, fill = Group)) + 
  geom_area() +
  scale_fill_manual(values = my_pal) +
  theme_void() +
  theme(legend.position = "none")
```

<!-- Image from README (as HTML link): -->

<!-- <p style="text-align:center;"> -->
<!-- <img src = "./../man/figures/README-usecol-ggplot2-1.png" alt = "pal_unikn" style = "width: 450px; border:10;"/> -->
<!-- </p> -->


## Resources

See the [Color recipes](https://hneth.github.io/unikn/articles/color_recipes.html) vignette 
(of the **[unikn](`r url_unikn_cran`)** package) for solving color-related tasks like:

- Viewing and comparing color palettes 
- Finding similar colors 
- Finding colors by name 
- Getting shades of a color
- Creating color gradients
- Creating new color palettes 


<!-- The following versions of **unikn** and corresponding resources are currently available:  -->

<!-- Type:                    | Version:           | URL:                           |          -->
<!-- :------------------------|:-------------------|:-------------------------------|  -->
<!-- A. **unikn** (R package): | [Release version](https://CRAN.R-project.org/package=unikn) | <https://CRAN.R-project.org/package=unikn> | -->
<!--     &nbsp;                | [Development version](https://github.com/hneth/unikn/)       | <https://github.com/hneth/unikn/> |  -->
<!-- B. Online documentation:  | [Release version](https://hneth.github.io/unikn/)            | <https://hneth.github.io/unikn/> |  -->
<!--     &nbsp;                | [Development version](https://hneth.github.io/unikn/dev/)    | <https://hneth.github.io/unikn/dev/> |  -->


## Vignettes

<!-- unicol pkg logo and link: -->
<a href = "`r url_unicol_cran`">
<img src = "../man/figures/logo.png" alt = "unicol::" align = "right" width = "150px" style = "width: 150px; float: right; border:0;"/>
</a>

The following vignettes provide an overview of and examples for using the **unicol** color palettes: 

<!-- Table of vignettes: -->

| Nr.  | Vignette | Content    |        
| ---: |:---------|:-----------|
| 1. | [All color palettes](color_pals.html) | The color palettes of the **unicol** R package |
| 2. | [Using color palettes](using_pals.html) | Recipes for using the **unicol** color palettes |


```{r restore-org-options, include = FALSE}
options(org_opt)  # restore original user options
```

<!-- eof. -->
