R: transparent colors using colorRampPalette

colors, plot, r, transparency

Solution

I would add the transparency after you generate the gradient, not before. You'll need to do this within your `csa` function, so consider adding an `alpha` argument to both `csa` and `color.scale.arrow`. Assuming you have done so, you can add the alpha transparency to the color gradient after generating it:

cols <- colorRampPalette( c(first.col,second.col))(250)
cols <- paste0(cols, alpha)

Also worth noting the alpha transparency is also hexadecimal: so `"50"` is not 50%, `"7f"` is.

Problem

I have the following code that draws arrows with a gradient: ``` csa <- function(x1,y1,x2,y2,first.col,second.col,length=0.15, ...) { cols <- colorRampPalette( c(first.col,second.col))(250) x <- approx(c(0,1),c(x1,x2), xout=seq(0,1,length.out=251))$y y <- approx(c(0,1),c(y1,y2), xout=seq(0,1,length.out=251))$y arrows(x[250],y[250],x[251],y[251], col=cols[250],length=length, ...) segments(x[-251],y[-251],x[-1],y[-1],col=cols, ...) } color.scale.arrow <- Vectorize(csa, c('x1','y1','x2','y2') ) # Create sample data x <- c(1,3,5,3,2,1,6,2) y <- c(2,5,3,7,2,1,5,6) x1 <- c(1,3,5,3) y1 <- c(2,5,3,7) x2 <- c(2,1,6,2) y2 <- c(2,1,5,6) # Plot sample data plot(x,y, main='') color.scale.arrow(x1,y1,x2,y2,'#5F9EA0','#CD3333',lwd=2) ``` Which produced this Figure: I want to make these lines transparent, but simply adding 50 to the colour code (i.e. proportion of transparency = 50%) does not work unfortunately: ``` # Plot sample data (transparent?) plot(x,y, main='') color.scale.arrow(x1,y1,x2,y2,'#5F9EA050','#CD333350',lwd=2) ``` Any idea why this doesn't work, and how to make these lines transparent?

Original source