【问题标题】:R - add transparency to rastergrob background of a ggplotR - 为 ggplot 的 rastergrob 背景添加透明度
【发布时间】:2017-04-11 15:17:56
【问题描述】:

我想为用作 ggplot 背景的 rastergrob 对象添加透明度。

这是我的代码

library(ggplot2)
library(grid)
library(ggthemes)

reds <- c("brown", "red","orange","green","orange","red","brown","grey")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1,"npc"),interpolate = TRUE)
p <- ggplot(data = economics, aes(x = date, y = unemploy)) +
  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)+
  geom_line( alpha=1, color = "white", size = 0.5 ) +
  xlab("Years") + ylab("Unemployed [thousands]") +
  theme_base() + 
  theme(panel.background=element_blank(),
        plot.background=element_blank(),        
        line = element_line(colour="white")) +
  theme()

grid.newpage()

print(p, newpage = FALSE)

我无法在 rastergrob 中添加 alpha,在 annotation_custom 中也没有。我已经找了一段时间了。

【问题讨论】:

  • 您尝试过使用数值吗?例如。而不是“红色”使用“#F5262688”
  • 嗯,是的,我找到了“adjustcolor”函数,它可以将我的向量的所有颜色转换为透明的等价物。谢谢!
  • 也许您可以发布自己问题的答案,以便人们知道该问题已得到解答。

标签: r ggplot2 background transparency


【解决方案1】:

scales::alpha() 是一种选择,

grid.newpage()
grid.text("background")

reds <- c("brown", "red","orange","green","orange","red","brown","grey")
grid.raster(scales::alpha(reds, 0.5), width = unit(1, "npc"), height = unit(1,"npc"),interpolate = TRUE)

【讨论】:

    【解决方案2】:

    我发现了一种可能的方法是使用函数adjustcolor(),它接受透明度“alpha”的参数和你的颜色列表并返回一个透明颜色列表

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 2016-06-21
      • 2021-11-15
      • 1970-01-01
      • 2021-12-30
      • 2014-02-21
      • 2022-01-23
      • 2018-01-07
      • 2018-02-12
      相关资源
      最近更新 更多