Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: add alpha-value to png-image

Tags:

r

image

Is there a way to make a rasterGrob-object partly transparent, so to add an alpha-factor to it? I'm using a logo as a watermark within a ggplot2 plot by inserting a png-image (as rasterGrob) by annotation_custom. However, unlike with annotate, the alpha option does not work here, so I guess the image has to be changed in advance.

As a simple example based on what baptiste suggests in his blog, so far I'm doing it this way:

img.path <- readPNG("logo.png")
pngob <- rasterGrob(img.path)
qplot(1:10, rnorm(10), geom = "blank") +
    annotation_custom(pngob, xmin=6.8, xmax=Inf, ymin=1, ymax=Inf) +
    geom_point()

The example above works perfectly.

However, typing dim(pngob) into the console returns NULL. Thus, the suggestion below on how to set an alpha-value does not work:

m <- pngob
w <- matrix(rgb(m[,,1],m[,,2],m[,,3], m[,,4] * 0.2), nrow=dim(m)[1])

This returns the error Error in m[, , 1]: wrong number of dimensions

like image 981
AnjaM Avatar asked Jul 06 '12 07:07

AnjaM


1 Answers

Straight from the ggplot2 blog by @baptiste. You can adjust alpha when you create w.

 library(png)
 library(gridExtra)
 m <- readPNG(system.file("img", "Rlogo.png", package="png"), FALSE)
 w <- matrix(rgb(m[,,1],m[,,2],m[,,3], m[,,4] * 0.2), nrow=dim(m)[1]) #0.2 is alpha


 qplot(1:10, rnorm(10), geom = "blank") +
      annotation_custom(xmin=-Inf, ymin=-Inf, xmax=Inf, ymax=Inf, 
         rpatternGrob(motif=w, motif.width = unit(1, "cm"))) +
      geom_point()

enter image description here

Or if you want to have a single image:

qplot(1:10, rnorm(10), geom = "blank") +
  annotation_custom(xmin=-Inf, ymin=-Inf, xmax=Inf, ymax=Inf, 
    rasterGrob(w)) +
  geom_point()

enter image description here

like image 139
Roman Luštrik Avatar answered Oct 20 '22 13:10

Roman Luštrik