2017-06-22 77 views
4

我想将自定义图像添加到每个构面。使用annotation_custom重复的图像在所有方面,e.g:将自定义图像添加到ggplot构面

require(ggplot2); require(grid); require(png); require(RCurl) 

p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species) 

img1 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png')) 
img2 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png')) 
img3 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png')) 

a1 = annotation_custom(rasterGrob(img1, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5) 
a2 = annotation_custom(rasterGrob(img2, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5) 
a3 = annotation_custom(rasterGrob(img3, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5) 

p + a1 

enter image description here

是否有其他方法来实现这一所以img1-3正确填充相应的层面呢?

+1

您可以通过@baptiste使用annotation_custom2功能。请参阅https://stackoverflow.com/questions/32807665/removing-one-tablegrob-when-applied-to-a-box-plot-with-a-facet-wrap?answertab=votes#tab-top –

+0

此外,此可能是有用的https://github.com/hrbrmstr/ggalt/issues/4 –

+0

整齐的黑客由@baptiste。感谢您的链接。想要填写答案?我的行是'a1 = annotation_custom2(rasterGrob(img1,interpolate = TRUE),xmin = 7,xmax = 8,ymin = 3.75,ymax = 4.5,data = iris [1,])' – geotheory

回答

1

为了完整,我添加了答案。所有功劳都归于@baptiste,他建议使用annotation_custom2函数。

require(ggplot2); require(grid); require(png); require(RCurl) 

p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species) 

img1 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png')) 
img2 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png')) 
img3 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png')) 


annotation_custom2 <- 
function (grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, data){ layer(data = data, stat = StatIdentity, position = PositionIdentity, 
     geom = ggplot2:::GeomCustomAnn, 
     inherit.aes = TRUE, params = list(grob = grob, 
              xmin = xmin, xmax = xmax, 
              ymin = ymin, ymax = ymax))} 

a1 = annotation_custom2(rasterGrob(img1, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[1,]) 
a2 = annotation_custom2(rasterGrob(img2, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[51,]) 
a3 = annotation_custom2(rasterGrob(img3, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[101,]) 

p + a1 + a2 + a3 

输出:

enter image description here

+0

也许明智的添加函数:) – geotheory

+0

上面编辑。谢谢@geotheory –