更改ggplot中背景图像的透明度

change transparency of background image in ggplot

我添加了背景图片,如何将背景图片的 alpha 设置为 0.5?

library(tidyverse)
library(png)
library(ggpubr)

tbl = tibble(x = runif(25),
          y = runif(25))

# read any image from computer for background
im = readPNG("temp.png")

ggplot(data = tbl, 
       aes(x = x, 
           y = y)) + 
  background_image(im) + 
  geom_point(color = "red",
             size = 5)

您需要在绘制之前设置 alpha

之前:

im <- readPNG("example.image.png")
im2 <- matrix(rgb(im[,,1],im[,,2],im[,,3], im[,,4] * 0.5), nrow=dim(im)[1]) ## you can change 0.5 to change the alpa

然后你可以应用这个:

library(png)
library(grid)
library(tibble)

ggplot(data = tbl, 
       aes(x = x, 
           y = y)) + 
  annotation_custom(rasterGrob(im2, 
                               width = unit(1,"npc"), 
                               height = unit(1,"npc")), 
                    -Inf, Inf, -Inf, Inf) +
  geom_point(color = "red",
             size = 5)

之后: