简体   繁体   English

R:使用colorRampPalette的透明色

[英]R: transparent colors using colorRampPalette

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 (ie proportion of transparency = 50%) does not work unfortunately: 我想让这些线条透明,但只是在颜色代码中添加50(即透明度的比例= 50%)不幸的是:

# 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? 知道为什么这不起作用,以及如何使这些线条透明?

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 . 您需要在csa函数中执行此操作,因此请考虑为csacolor.scale.arrow添加alpha参数。 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. 另外值得注意的是,alpha透明度也是十六进制的:所以"50"不是50%, "7f"是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM