是否可以使用ggplot创建多个数据和图像?

Lyn*_*nda 7 r ggplot2

我想知道是否可以使用ggplot2创建一个包含图像的多图(如facet):

我想要什么

我不知道如何安排图像数据传递给它们geom_raster()或如何在数据框中包含图像......

我试过的:

> img1 <- readPNG('1.png')
> img2 <- readPNG('2.png')
> img3 <- readPNG('3.png')

> test <- data.frame(c(1,2,3),c(5,2,7),c(img1,img2,img3))
> nrow(test)
 [1] 4343040
Run Code Online (Sandbox Code Playgroud)

我已经有了一个问题,建立一个内部图像的数据框...每3行重复一次(我想每像素一次).

Lyn*_*nda 5

我最终使用了这个将绘图分解为 gtable 的解决方案,再添加一行并插入图像。当然,一旦分解,就不能再给情节添加更多的层次,所以它应该是最后的操作。我不认为 gtable 可以转换回绘图。

library(png)
library(gridExtra)
library(ggplot2)
library(gtable)
library(RCurl) # just to load image from URL

#Loading images
img0 <- readPNG(getURLContent('http://i.stack.imgur.com/3anUH.png'))
img1 <- readPNG(getURLContent('http://i.stack.imgur.com/3anUH.png'))

#Convert images to Grob (graphical objects)
grob0 <- rasterGrob(img0)
grob1 <- rasterGrob(img1)

# create the plot with data
p <- ggplot(subset(mpg,manufacturer=='audi'|manufacturer=='toyota'),aes(x=cty,y=displ))+facet_grid(year~manufacturer)+geom_point()

# convert the plot to gtable
mytable <- ggplot_gtable(ggplot_build(p))

#Add a line ssame height as line 4 after line 3
# use gtable_show_layout(mytable) to see where you want to put your line
mytable <- gtable_add_rows(mytable, mytable$height[[4]], 3)
# if needed mor row can be added 
# (for example to keep consistent spacing with other graphs)

#Insert the grob in the cells of the new line
mytable <- gtable_add_grob(mytable,grob0,4,4, name = paste(runif(1)))
mytable <- gtable_add_grob(mytable,grob1,4,6, name = paste(runif(1)))

#rendering
grid.draw(mytable)
Run Code Online (Sandbox Code Playgroud)

结果

注意:在这个例子中,我使用了两次相同的图像,但当然可以根据需要使用尽可能多的图像。

灵感来自:如何为 ggplot2 中的 facet 添加通用标签?