Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - add transparency to colorRampPalette

Tags:

r

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?

like image 850
CodeGuy Avatar asked May 13 '14 00:05

CodeGuy


2 Answers

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.

like image 65
Scott Ritchie Avatar answered Oct 19 '22 08:10

Scott Ritchie


Here is my inelegant way to create a transparent palette with colorRampPalette

## first specify your color scheme

colorRampPalette(c("lightgrey","grey","lightblue","blue","darkblue"))  -> blues

## Then create the palette as you would normally
blues_pal<-blues(500)

## Finally use paste to set transparency to every color in the vector
blues_pal_transp<-paste(blues_pal, "50", sep="")

## and an example
image(volcano, col=blues_pal_transp)
like image 2
atlantach_james Avatar answered Oct 19 '22 06:10

atlantach_james