2

假设我正在为 4 个人绘制数据:Alice、Bob、Chuck 和 Dana。我正在使用 ggplot2 制作一个多面图,每人一个面。我在磁盘上还有 4 个图像:Alice.png、Bob.png、Chuck.png 和 Dana.png。(显然这是一个综合示例,需要扩展到超过 4 个方面 :)

有没有办法可以用相应的图像来注释每个方面,理想情况下,而不是分面标签(尽管我会对标签正下方的图像感到满意)?也许类似于这里使用的技术:Use image instead of labels in ggplot2 legend ? 我已经尝试阅读各种注释方法的文档,但我的 R-fu 不足以应对挑战!

4

1 回答 1

5

不是很优雅,但您可以在条形标签上添加 grobs,

library(ggplot2)

d <- expand.grid(x=1:2,y=1:2, f=letters[1:2])
p <- qplot(x,y,data=d) + facet_wrap(~f)

g <- ggplot_gtable(ggplot_build(p))

library(gtable)
library(RCurl)
library(png)
shark <- readPNG(getURLContent("http://i.imgur.com/EOc2V.png"))
tiger <- readPNG(getURLContent("http://i.imgur.com/zjIh5.png"))

strips <- grep("strip", g$layout$name)
new_grobs <- list(rasterGrob(shark, width=1, height=1),
                  rasterGrob(tiger, width=1, height=1))
g <- with(g$layout[strips,],
          gtable_add_grob(g, new_grobs,
                          t=t, l=l, b=b, r=r, name="strip_predator") )        
grid.draw(g)

编辑:您也可以直接替换 grobs,

strips <- grep("strip", names(g$grobs))
new_grobs <- list(rectGrob(gp=gpar(fill="red", alpha=0.2)),
                  rectGrob(gp=gpar(fill="blue", alpha=0.2)))
g$grobs[strips] <- new_grobs
grid.draw(g)
于 2012-10-31T06:31:43.857 回答