当使用颜色参数时更改R{graphics}中的alpha值

6

我太习惯在ggplot2中做这个了,所以我很难想象如何在R基础图形中指定alpha值,而plot()中的col =参数用于为分类变量分配颜色类型。

使用鸢尾花数据集(虽然在这种情况下更改alpha值没有什么意义)

data(iris)
library(ggplot2)
g <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species), alpha=0.5) #desired plot

plot(iris$Sepal.Length, iris$Petal.Length, col=iris$Species) #attempt in base graphics

你可以使用{graphics}将另一个变量映射到alpha值上。 例如,在ggplot2中:

g2 <- ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point(aes(colour=Species, alpha=Petal.Width)) 

非常感谢您的帮助!

2个回答

12

使用 adjustcolor 函数调整 alpha 值非常容易:

COL <- adjustcolor(c("red", "blue", "darkgreen")[iris$Species], alpha.f = 0.5)
plot(iris$Sepal.Length, iris$Petal.Length, col = COL, pch = 19, cex = 1.5) #attempt in base graphics

这里输入图片描述

将 alpha 映射到变量需要进行更多的技巧处理:

# Allocate Petal.Length to 7 length categories
seq.pl <- seq(min(iris$Petal.Length)-0.1,max(iris$Petal.Length)+0.1, length.out = 7)

# Define number of alpha groups needed to fill these
cats <- nlevels(cut(iris$Petal.Length, breaks = seq.pl))

# Create alpha mapping
alpha.mapping <- as.numeric(as.character(cut(iris$Petal.Length, breaks = seq.pl, labels = seq(100,255,len = cats))))

# Allocate species by colors
COLS <- as.data.frame(col2rgb(c("red", "blue", "darkgreen")[iris$Species]))

# Combine colors and alpha mapping
COL <- unlist(lapply(1:ncol(COLS), function(i) {
  rgb(red = COLS[1,i], green = COLS[2,i], blue = COLS[3,i], alpha = alpha.mapping[i], maxColorValue = 255)
  }))

# Plot
plot(iris$Sepal.Length, iris$Petal.Length, col = COL, pch = 19, cex = 1.5) 

这里输入图像描述


我猜如果我之前找到这个链接的话,它也会很有用!http://lamages.blogspot.ca/2013/04/how-to-change-alpha-value-of-colours-in.html - user3389288

4
您可以尝试使用adjustcolor函数。
例如:
getColWithAlpha <- function(colLevel, alphaLevel)
{
  maxAlpha <- max(alphaLevel)
  cols <- rainbow(length(levels(colLevel)))
  res <- cols[colLevel]
  sapply(seq(along.with=res), function(i) adjustcolor(res[i], alphaLevel[i]/maxAlpha) )
}

 plot(iris$Sepal.Length, iris$Petal.Length, 
      col = getColWithAlpha(iris$Species, iris$Petal.Width), pch = 20)

希望能有所帮助, alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接