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
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With