mix_colors: Mix n colors using values of 'x' as weights

Description Usage Arguments Details Value See Also Examples

View source: R/figures_functions_miscellaneous.R

Description

Mix n colors using values of x as weights

Usage

1

Arguments

x

A two-dimensional numerical object. Each row produces one mixed color. The number of columns must correspond to the number of colors.

colors

A vector, list, or two-dimensional object of colors to be mixed. If a two-dimensional object, then the columns must represent the red, green, and blue values of RGB colors (see rgb). If a vector or list, then colors must be specified in on of the formats supported by col2rgb.

Details

Any NA value in a row of x will translate to a corresponding NA in the returned vector.

Value

A vector of the mixed colors. The format is R's hexadecimal color codes #rrggbb (see rgb), which can be used as col = argument of graphics functions or in par.

See Also

mixcolor for mixing two colors.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
## Mixing some colors
xw <- rbind(
  c(0.5, 0.25, 0.25, 0),
  c(0.25, 0, 0.75, 0),
  c(0, 0, 1, 0),
  c(1, 0, 0, 0),
  c(0.25, 0.25, 0.25, 0.25),
  c(0.1, 0.1, 0.1, 0.7)
)
cols <- c("red", "orange", "purple", "yellow")

# Example where `colors` is a vector of color names
mix_colors(x = xw, colors = cols)

# Example where `colors` is a list of color names
mix_colors(x = xw, colors = as.list(cols))

if (requireNamespace("grDevices")) {
  # Example where `colors` is a list of hexadecimal color codes #rrggbb
  mix_colors(
    x = xw,
    colors = lapply(
      cols,
      function(col) {
        col <- t(grDevices::col2rgb(col))
        grDevices::rgb(col, maxColorValue = 255)
      }
    )
  )

  # Example where `colors` is a matrix of RGB colors
  mix_colors(x = xw, colors = t(grDevices::col2rgb(cols)))
}


## Mixing two colors produces almost the same results as the
## function `mixcolor` (but not exactly due to rounding to integers when
## converting to the 255-scale used by `col2rgb`)

if (requireNamespace("colorspace")) {
  res1 <- colorspace::mixcolor(
    alpha = 0.25,
    colorspace::RGB(1, 0, 0),
    colorspace::RGB(0, 1, 0)
  )
  res1 <- colorspace::coords(res1)

  res2 <- mix_colors(
    x = c(0.75, 0.25),
    colors = list(
      grDevices::rgb(1, 0, 0),
      grDevices::rgb(0, 1, 0)
    )
  )
  res2 <- grDevices::col2rgb(res2)
  res2 <- res2 / sum(res2)

  isTRUE(all.equal(as.vector(res1), as.vector(res2), tolerance = 1 / 254))
}

DrylandEcology/rSW2analysis documentation built on Nov. 8, 2021, 4:20 p.m.