Transparent equivalent of given color
There is a function adjustcolor
in grDevices
package, that works like this in your case:
adjustcolor( "red", alpha.f = 0.2)
Have you had a look at ?rgb
?
Usage:
rgb(red, green, blue, alpha, names = NULL, maxColorValue = 1)
An alpha transparency value can also be specified (as an opacity, so ‘0’ means fully transparent and ‘max’ means opaque). If alpha’ is not specified, an opaque colour is generated.
The alpha
parameter is for specifying transparency. col2rgb
splits R colors specified in other ways into RGB so you can feed them to rgb
.
I think is more common to specify alpha
in [0,1]
. This function do that, plus accept several colors as arguments:
makeTransparent = function(..., alpha=0.5) {
if(alpha<0 | alpha>1) stop("alpha must be between 0 and 1")
alpha = floor(255*alpha)
newColor = col2rgb(col=unlist(list(...)), alpha=FALSE)
.makeTransparent = function(col, alpha) {
rgb(red=col[1], green=col[2], blue=col[3], alpha=alpha, maxColorValue=255)
}
newColor = apply(newColor, 2, .makeTransparent, alpha=alpha)
return(newColor)
}
And, to test:
makeTransparent(2, 4)
[1] "#FF00007F" "#0000FF7F"
makeTransparent("red", "blue")
[1] "#FF00007F" "#0000FF7F"
makeTransparent(rgb(1,0,0), rgb(0,0,1))
[1] "#FF00007F" "#0000FF7F"
makeTransparent("red", "blue", alpha=0.8)
[1] "#FF0000CC" "#0000FFCC"
Converting valuable comment to answer:
Use alpha
from package scales
- first argument is colour, second alpha (in 0-1 range).
Or write function overt it:
makeTransparent <- function(someColor, alpha=100) scales::alpha(someColor, alpha/100)