How to change the alpha value of colours in R

4 comments
Often I like to reduce the alpha value (level of transparency) of colours to identify patterns of over-plotting when displaying lots of data points with R. So, here is a tiny function that allows me to add an alpha value to a given vector of colours, e.g. a RColorBrewer palette, using col2rgb and rgb, which has an argument for alpha, in combination with the wonderful apply and sapply functions.


The example below illustrates how this function can be used with colours provided in different formats, thanks to the col2rgb function.



Session Info

sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RCurl_1.95-4.1 bitops_1.0-5

4 comments :

anspiess said...

Short and cool function!

hans said...

i like to use ggplot2, it has built-in functions to do the same thing

library(ggplot2)
ggplot(dat, aes(x = x, y = y)) + #set up plot with data source and axis
geom_boxplot(outlier.colour=NA) + # add boxplots, suppress outliers
geom_point(position = "jitter", aes(col = factor(x)), alpha = .5) + #add jittered points, #colored by y, set alpha to .5
theme_bw() + # i prefer the bw theme
scale_color_brewer(type = "qual", palette = 6) # set color palette

Marek said...

There is adjustcolor function: adjustcolor(myColours, 0.4)

Markus Gesmann said...

Brilliant! I didn't know this function existed.

Post a Comment