R:使用colorRampPalette的透明色

Abd*_*del 3 plot transparency r colors

我有以下代码用渐变绘制箭头:

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)
Run Code Online (Sandbox Code Playgroud)

哪个产生了这个图:

在此输入图像描述

我想让这些线条透明,但只是在颜色代码中添加50(即透明度的比例= 50%)不幸的是:

# Plot sample data (transparent?)
plot(x,y, main='')
color.scale.arrow(x1,y1,x2,y2,'#5F9EA050','#CD333350',lwd=2)
Run Code Online (Sandbox Code Playgroud)

知道为什么这不起作用,以及如何使这些线条透明?

Sco*_*hie 5

我会在生成渐变之后添加透明度,而不是之前.你需要你的内做到这一点csa的功能,所以考虑加入一个alpha参数都csacolor.scale.arrow.假设您已经这样做了,可以在生成颜色渐变后将其添加到颜色渐变中:

cols <- colorRampPalette( c(first.col,second.col))(250)
cols <- paste0(cols, alpha)
Run Code Online (Sandbox Code Playgroud)

另外值得注意的是,alpha透明度也是十六进制:所以"50"不是50%,"7f"是.

  • 你必须在`csa()`中对`cols`这样做 (3认同)