任何方法使散点图中的绘图点在R中更加透明?

时间:2012-10-21 06:58:04

标签: r plot ggplot2 alpha

我有一个3列矩阵;图表是基于第1列和第2列值的点,但是基于第2列(6个不同的组)着色。我可以成功地绘制所有点,但是,最后一个分组颜色为紫色的绘图组(组6)掩盖了其他组的绘图。有没有办法让情节点更透明?

s <- read.table("/.../parse-output.txt", sep="\t") 
dim(s) 
[1] 67124     3
x <- s[,1] 
y <- s[,2]
z <- s[,3] 
cols <- cut(z, 6, labels = c("pink", "red", "yellow", "blue", "green", "purple"))
plot(x, y, main= "Fragment recruitment plot - FR-HIT", ylab = "Percent identity", xlab = "Base pair position", col = as.character(cols), pch=16) 

5 个答案:

答案 0 :(得分:73)

否则,您在alpha包中有一个功能scales,您可以在其中直接输入颜色矢量(即使它们是您的示例中的因素):

library(scales)
cols <- cut(z, 6, labels = c("pink", "red", "yellow", "blue", "green", "purple"))
plot(x, y, main= "Fragment recruitment plot - FR-HIT", 
     ylab = "Percent identity", xlab = "Base pair position", 
     col = alpha(cols, 0.4), pch=16) 
# For an alpha of 0.4, i. e. an opacity of 40%.

答案 1 :(得分:39)

创建颜色时,您可以使用rgb并设置其alpha参数:

plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
     pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
       pch = 16, cex = 4)

enter image description here

有关详细信息,请参阅?rgb

答案 2 :(得分:16)

透明度也可以在颜色参数中编码。它只是两个十六进制数字,编码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)

答案 3 :(得分:11)

如果您决定使用ggplot2,则可以使用alpha参数设置重叠点的透明度。

e.g。

library(ggplot2)
ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 1/40)

答案 4 :(得分:8)

如果您使用的是十六进制代码,则可以在代码末尾再添加两位数来表示Alpha通道:

E.g。半透明红色:

plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")

example plot of color with transparency