R - add transparency to colorRampPalette
r
Solution
You just need to add `alpha=TRUE` to your call to `colorRampPalette`:
>?colorRampPalette
alpha: logical: should alpha channel (opacity) values should be
returned? It is an error to give a true value if ‘space’ is
specified.
> colorRampPalette(c(rgb(1,1,1,0.5),rgb(1,0,0,0.5)))(3)
[1] "#FFFFFF" "#FF7F7F" "#FF0000"
> colorRampPalette(c(rgb(1,1,1,0.5),rgb(1,0,0,0.5)), alpha=TRUE)(3)
[1] "#FFFFFF80" "#FF7F7F80" "#FF000080"
Since your `colorRampPalette` doesn't seem to have the `alpha` argument, here's a manual solution:
# Specify alpha as a percentage:
colorRampAlpha <- function(..., n, alpha) {
colors <- colorRampPalette(...)(n)
paste(colors, sprintf("%x", ceiling(255*alpha)), sep="")
}
colorRampAlpha(c(rgb(1,1,1),rgb(1,0,0)), n=3, alpha=0.5)
[1] "#FFFFFF80" "#FF7F7F80" "#FF000080"
You'll need to specify the number of colors you want in advance however.
Problem
I'm using `smoothScatter` to plot some data. I'm trying to change the color of the density from the default of `colorRampPalette(c("white", blues9)` to transparent red. How can I do this? I tried: ``` smoothScatter( x,y,nrpoints=length(df$x), colramp = colorRampPalette(c(rgb(1,1,1,0.5),rgb(1,0,0,0.5)) ) ``` But this doens't work. More generally put, how can I create a `colorRampPalette` function that can be passed in as a function that includes making all the colors transparent?