Thursday, April 19, 2012

Adding a transparent image layer to a plot

The following example shows how to add a transparent image-type layer to a plot. The add.alpha function (below) simply adds transparency to a vector of colors which is then introduced in the "col" argument of an image plot.

add.alpha function
add.alpha <- function(COLORS, ALPHA){
 if(missing(ALPHA)) stop("provide a value for alpha between 0 and 1")
 RGB <- col2rgb(COLORS, alpha=TRUE)
 RGB[4,] <- round(RGB[4,]*ALPHA)
 NEW.COLORS <- rgb(RGB[1,], RGB[2,], RGB[3,], RGB[4,], maxColorValue = 255)
Created by Pretty R at

to reproduce the example...
png("transparent_poly.png", width=4, height=4, res=200, units="in")
par(mar=c(4,4,1,1), ps=8)
x <- seq(-180, 180,, 30)
y <- seq(-90, 90,, 30)
grd <- expand.grid(x=x,y=y)
z <- sqrt(grd$x^2+grd$y^2)
dim(z) <- c(length(x), length(y))
pal <- colorRampPalette(c(rgb(1,1,1), rgb(0,0,0)))
COLORS <- pal(20)
image(x,y,z, col=COLORS)
z2 <- grd$x^2+grd$y
dim(z2) <- c(length(x), length(y))
pal <- colorRampPalette(c(rgb(0.5,1,0), rgb(0,1,1), rgb(1,1,1)))
COLORS <- add.alpha(pal(20), 0.4)
image(x,y,z2, col=COLORS, add=TRUE)
Created by Pretty R at

1 comment:

  1. Thank you thank you thank you! I've been struggling with searching for a solution for a while,a nd this works perfectly!