本文介绍了将自定义图像添加到ggplot构面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想向每个方面添加自定义图像.使用annotation_custom
可在所有方面复制图像,例如:
I'd like to add a custom image to each facet. Using annotation_custom
duplicates an image across all facets, e.g:
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
是否有另一种方法可以做到这一点,以便img1-3
正确填充各个方面?
Is there an alternative method to achieve this so img1-3
populate the respective facets correctly?
推荐答案
为完整起见,我添加了答案.所有贡献归功于@baptiste,他建议了annotation_custom2函数.
For completeness, I'm adding the answer. All credit goes to @baptiste who suggested the annotation_custom2 function.
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
输出:
这篇关于将自定义图像添加到ggplot构面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!