首页 > 解决方案 > 将图像背景添加到 ggplot barplot 以便图像仅在条形图内可见

问题描述

我想使用 ggplot2 在 R 中创建一个条形图,以便条形图是透明的,允许背景图像可见,而图的其余部分是不透明的并覆盖背景图像。

我可以将图像添加到背景中,如下所示,但我找不到仅在条形图中显示背景图像的方法。从本质上讲,我希望创造出与我在这里所拥有的相反的东西。

library(ggplot2)
library(jpeg)
library(grid)
library(scales)

montage <- readJPEG("AcanthMontage.jpg")
mont <- rasterGrob(montage, 
                   width = unit(1,"npc"), 
                   height = unit(1,"npc"))

montplot <- ggplot(frequencyDF, aes(x=depth, y= perLiter)) + 
  annotation_custom(mont, -Inf, Inf, -Inf, Inf) +
  scale_fill_continuous(guide = FALSE) +
  geom_bar(stat = "identity", color="black", fill="white", alpha=0.5) + 
  coord_flip() + 
  scale_y_continuous(limits= c(0,1.25), expand = c(0, 0)) + 
  scale_x_continuous(limits= c(-1000,0), expand = c(0,0)) + 
  theme_bw() + 
  theme(text=element_text(size=16)) + 
  xlab("Depth (m)") + 
  ylab("Cells per Liter")

montplot

以图像为背景的ggplot

标签: rggplot2geom-bar

解决方案


这让我想起了这里的一个类似问题,其中公认的解决方案用于geom_ribbon()提供遮罩层。

以类似的方式进行,因为在这种情况下蒙版需要围绕单个条,我们正在寻找一个可以优雅地处理孔的多边形层。最后我检查了一下,效果geom_polygon不是很好,但是geom_polypath来自 ggpolypath 包。

可重现的示例,使用 R 徽标作为示例图像和内置数据框:

library(ggplot2)
library(grid)
library(jpeg)

montage <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))
mont <- rasterGrob(montage, width = unit(1,"npc"), 
                   height = unit(1,"npc"))

p <- ggplot(mpg, aes(x = class)) +
  annotation_custom(mont, -Inf, Inf, -Inf, Inf) +
  geom_bar(color = "black", fill = NA) +
  coord_flip() +
  theme_bw()

p

情节 1

为遮罩层创建坐标数据框:

library(dplyr)
library(tidyr)

# convert the xmin/xmax/ymin/ymax values for each bar into
# x/y coordinates for a hole in a large polygon,
# then add coordinates for the large polygon

new.data <- layer_data(p, 2L) %>%  

  select(ymin, ymax, xmin, xmax) %>%
  mutate(group = seq(1, n())) %>%
  group_by(group) %>%
  summarise(coords = list(data.frame(x = c(xmin, xmax, xmax, xmin),
                                     y = c(ymin, ymin, ymax, ymax),
                                     order = seq(1, 4)))) %>%
  ungroup() %>%
  unnest() %>%

  rbind(data.frame(group = 0,
                   x = c(-Inf, Inf, Inf, -Inf),
                   y = c(-Inf, -Inf, Inf, Inf),
                   order = seq(1, 4)))

> new.data
# A tibble: 32 x 4
   group     x     y order
   <dbl> <dbl> <dbl> <int>
 1     1  0.55     0     1
 2     1  1.45     0     2
 3     1  1.45     5     3
 4     1  0.55     5     4
 5     2  1.55     0     1
 6     2  2.45     0     2
 7     2  2.45    47     3
 8     2  1.55    47     4
 9     3  2.55     0     1
10     3  3.45     0     2
# ... with 22 more rows

添加遮罩层:

library(ggpolypath)

p +
  geom_polypath(data = new.data,
                aes(x = x, y = y, group = group),
                inherit.aes = FALSE, 
                rule = "evenodd",
                fill = "white", color = "black")

情节2

ps 古老的格言“仅仅因为你可以,并不意味着你应该”在这里可能适用......


推荐阅读