R:将Alpha值添加到png图像 [英] R: add alpha-value to png-image

查看:125
本文介绍了R:将Alpha值添加到png图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使rasterGrob对象部分透明,从而为其添加alpha因子?我在ggplot2图中使用徽标作为水印,方法是通过annotation_custom插入png图像(作为rasterGrob).但是,与annotate不同的是,alpha选项在这里不起作用,因此我认为必须提前更改图像.

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.

作为一个简单的示例,该示例基于baptiste在他的博客中的建议,到目前为止,我是这样做的:

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()

上面的例子很好用.

但是,在控制台中键入dim(pngob)会返回NULL.因此,以下有关如何设置alpha值的建议不起作用:

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])

这将返回错误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()

这篇关于R:将Alpha值添加到png图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆