You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot中如何设置背景图片的alpha透明度为0.5

解决方法

有两种常用的实现方案:

  • 方案1:直接修改读取到的图片数组的透明度,适配ggpubr::background_image的使用逻辑
    png::readPNG()读取到的png图片是矩阵数组,如果是无透明通道的RGB图片会返回维度为[高度, 宽度, 3]的数组,手动添加第4维作为alpha通道统一赋值为0.5即可。如果原图本身带透明通道,直接将第4维数值乘以0.5就可以降低整体透明度。
    代码修改如下:
    library(tidyverse)
    library(png)
    library(ggpubr)
    
    tbl = tibble(x = runif(25),
              y = runif(25))
    
    im = readPNG("temp.png")
    # 新增/修改alpha通道
    if (dim(im)[3] == 3) {
      # 原图无透明通道,新增alpha层
      im <- array(c(im, rep(0.5, dim(im)[1]*dim(im)[2])), dim = c(dim(im)[1:2], 4))
    } else {
      # 原图已有透明通道,统一调整透明度
      im[,,4] <- im[,,4] * 0.5
    }
    
    ggplot(data = tbl, 
           aes(x = x, 
               y = y)) + 
      background_image(im) + 
      geom_point(color = "red",
                 size = 5)
    
  • 方案2:使用ggplot2原生的annotation_raster()函数添加背景,直接支持alpha参数设置,不需要修改原图数组
    该方案不需要额外依赖ggpubr包,调整参数也更灵活,更推荐使用。代码修改如下:
    library(tidyverse)
    library(png)
    
    tbl = tibble(x = runif(25),
              y = runif(25))
    
    im = readPNG("temp.png")
    
    ggplot(data = tbl, 
           aes(x = x, 
               y = y)) + 
      # x和y范围设为正负Inf保证铺满整个绘图区域,直接设置alpha参数即可
      annotation_raster(im, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.5) +
      geom_point(color = "red",
                 size = 5)
    

内容的提问来源于stack exchange,提问作者SiH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:54:00