Changing the alpha values in R{graphics} while the colour argument is used -
i'm used doing in ggplot2 i'm having hard time figuring out how specify alpha values using r base graphics, while col= argument in plot() used assigning colour type categorical variable.
using iris data set (although in context doesn't make sense why need 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
what mapping variable alpha value using {graphics}? example in ggplot2:
g2 <- ggplot(iris, aes(sepal.length, petal.length)) + geom_point(aes(colour=species, alpha=petal.width))
any appreciated!
adjusting alpha pretty easy 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
mapping alpha variable requires bit more hacking:
# allocate petal.length 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 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 colors cols <- as.data.frame(col2rgb(c("red", "blue", "darkgreen")[iris$species])) # combine colors , 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)
Comments
Post a Comment