Changing alpha values ​​in R {graphics} while using color argument

I’m so used to doing this in ggplot2, it’s very difficult for me to figure out how to specify alpha values ​​using the basic R plot, while the col = argument in plot () is used to assign the color type to the categorical variable.

Using an aperture dataset (although in this context it really doesn't make sense why we need to change alpha values)

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 

How to map another variable to alpha value using {graphics}? For example, in ggplot2:

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

Any help is appreciated!

+6
source share
2 answers

Setting alpha is pretty simple with the adjustcolor function:

 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

Displaying an alpha variable requires a bit more hacking:

 # 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

+8
source

You can try using the adjustcolor function

For instance:

 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) 

Hope this helps,

Alex

+3
source

All Articles