Make transparent colors in R

You can easily make transparent colors using R and the rgb() command. These colors can be useful for charts and graphics with overlapping elements.

The rgb() command is the key: you define a new color using numerical values (0–255) for red, green and blue. In addition, you set an alpha value (also 0–255), which sets the transparency (0 being fully transparent and 255 being “solid”).

You also need to set the maximum color value, so that the command can relate your alpha value to a level of transparency. In practice setting max = 255 works well (since RGB colors are usually defined in the range 0–255).

The following example takes the standard blue and makes it transparent (~50%):

mycol <- rgb(0, 0, 255, max = 255, alpha = 125, names = "blue50")

Note that the names parameter sets a name attribute for your color. You cannot use the name directly but it can be useful to see a name, e.g.

> mycol
     blue50
"#0000FF7D"

Get the RGB values

Use the col2rgb() command to get the red, green and blue values you need for the rgb() command e.g.:

> col2rgb("lightblue")
      [,1]
red    173
green  216
blue   230

This gives you a matrix with three rows (red, blue, green). This means you can get values for several colors at once:

> col2rgb(c("lightblue", "lightgreen", "pink"))
      [,1] [,2] [,3]
red    173  144  255
green  216  238  192
blue   230  144  203

Custom function for transparent colors

It is fairly easy to make a custom function that takes a named color and makes a transparent version. Here is some code that makes a single color. It could be extended to make a matrix of several colors quite easily:

## Transparent colors
## Mark Gardener 2015
## www.dataanalytics.org.uk

t_col <- function(color, percent = 50, name = NULL) {
  #      color = color name
  #    percent = % transparency
  #       name = an optional name for the color

## Get RGB values for named color
rgb.val <- col2rgb(color)

## Make new color using input color as base and alpha set by transparency
t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3],
             max = 255,
             alpha = (100 - percent) * 255 / 100,
             names = name)

## Save the color
invisible(t.col)
}
## END

Example of using transparent color

Here is a quick example of the function in action:

> opar <- par(mfrow = c(1,2))
> set.seed(1)
> hist(rnorm(100), col = "pink")
> mycol <- t_col("pink", perc = 50, name = "lt.pink")
> hist(rnorm(100), col = mycol)
> par(opar)
Comments are closed.