透明度也可以在颜色参数中编码。它只是另外两个十六进制数字,编码介于 0(完全透明)和 255(完全可见)之间的透明度。我曾经写过这个函数来为颜色向量添加透明度,也许它在这里有用?
addTrans <- function(color,trans)
{
# This function adds transparancy to a color.
# Define transparancy with an integer between 0 and 255
# 0 being fully transparant and 255 being fully visable
# Works with either color and trans a vector of equal length,
# or one of the two of length 1.
if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))
num2hex <- function(x)
{
hex <- unlist(strsplit("0123456789ABCDEF",split=""))
return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
}
rgb <- rbind(col2rgb(color),trans)
res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
return(res)
}
一些例子:
cols <- sample(c("red","green","pink"),100,TRUE)
# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)
# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)
# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)