首页 文章

使用颜色参数时更改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

使用将另一个变量映射到alpha值怎么样?例如在ggplot2中:

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

任何帮助表示赞赏!

2 回答

  • 10

    使用 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
    

    enter image description here

    将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)
    

    enter image description here

  • 3

    您可以尝试使用 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)
    

    希望能帮助到你,

    亚历克斯

相关问题