用图像注释ggplot2方面 [英] Annotate ggplot2 facets with images

查看:90
本文介绍了用图像注释ggplot2方面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在为4个人绘制数据:Alice,Bob,Chuck和Dana。我正在使用ggplot2来制作一个每个人都有一个方面的曲面情节。我在磁盘上还有4张图片:Alice.png,Bob.png,Chuck.png和Dana.png。 (显然这是一个综合示例,需要扩展到4个以上的方面:)

有没有一种方法可以用相应的图像对每个方面进行注释,理想的情况是(尽管我对标签下面的图片感到满意)?也许类似于此处使用的技术:在ggplot2图例中使用图像而不是标签?我已经尝试阅读各种批注方法的文档,但是我的R-fu不足以应对挑战!

解决方案

不是非常优雅,但您可以在条形标签顶部添加grobs,

  library(ggplot2)

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

g< - ggplot_gtable(ggplot_build(p))

图书馆(gtable)
图书馆(RCurl)
图书馆(png)
shark< - readPNG(getURLContent(http://i.imgur.com/EOc2V.png))
tiger< - readPNG(getURLContent(http://i.imgur.com/ (鲨鱼,宽度= 1,高度= 1))
$ b $ strip new_grobs< - list 1),
rasterGrob(tiger,width = 1,height = 1))
g < - with(g $ layout [strips,],
gtable_add_grob(g,new_grobs,
t = t,l = 1,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)


Say I'm graphing data for 4 people: Alice, Bob, Chuck and Dana. I'm using ggplot2 to make a faceted plot with one facet per person. I also have 4 images on disk: Alice.png, Bob.png, Chuck.png and Dana.png. (obviously this is a synthetic example that would need to scale to more than 4 facets :)

Is there a way I can annotate each facet with the corresponding image, ideally instead of the facet label (although I'd be happy with the image right below the label)? Perhaps something similar to the technique used here: Use image instead of labels in ggplot2 legend ? I've tried reading through the documentation for the various annotate methods but my R-fu is insufficient to the challenge!

解决方案

Not very elegant, but you can add grobs on top of the strip labels,

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)

Edit: you can also replace directly the 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)

这篇关于用图像注释ggplot2方面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆