自定义图像如何展示为geom_point?

25

在 R ggplot 中,是否可以将自定义图像(例如 png 格式)显示为 geom_point?

library(png)
pic1 <- readPNG("pic1.png")

png("Heatmap.png", units="px", width=3200, height=3200, res=300)
ggplot(data_frame, aes(medium, day, fill = Transactions))  +
   geom_tile(colour="white")  +
   facet_grid(dime3_year~dime3_month) + 
   scale_fill_gradient(high="blue",low="white") +
   theme_bw() + 
   geom_point(aes(dime3_channel, day, size=Conv,alpha=Conv,image=(annotation_raster(pic1,xmin=0,ymin=0,xmax=5,ymax=5)),color="firebrick")) +

产生错误:

不知道如何自动选择类型为proto/environment的对象的比例尺。默认为连续型。错误:美学映射必须是长度为一或与数据长度相同。问题所在:(annotation_raster(conv_pic, xmin = 0, ymin = 0, xmax = 5, ymax = 5))


1
我会从 grImport 包开始。可能需要一些 grid 调整。 - joran
2
另请参见 grImport2,例如第一个示例此处或使用lattice的图11 此处。有关grImport的精彩文章此处(例如,请参见图8,也使用了lattice)。 - Henrik
请参考以下网址:https://dev59.com/MpXfa4cB1Zd3GeqPckim - baptiste
请返回已翻译的文本。 - baptiste
2个回答

15

点几何图形用于创建散点图,似乎并不完全适合您所需的内容,即显示自定义图片。然而,类似的问题已经在这里得到解答,指出可以通过以下步骤解决问题:

(1) 读取您想要显示的自定义图片,

(2) 使用rasterGrob()函数在给定位置、大小和方向上呈现栅格对象,

(3) 使用像qplot()这样的绘图函数,

(4) 使用像annotation_custom()这样的几何图形作为静态注释,指定x和y限制的粗略调整,正如user20650所提到的那样。

使用下面的代码,我可以在给定的xmin、xmax、ymin和ymax位置获得两个自定义图片img1.png和img2.png。

library(png)
library(ggplot2)
library(gridGraphics)
setwd("c:/MyFolder/")

img1 <- readPNG("img1.png")
img2 <- readPNG("img2.png")
g1 <- rasterGrob(img1, interpolate=FALSE)
g2 <- rasterGrob(img2, interpolate=FALSE)
qplot(1:10, 1:10, geom="blank") + 
  annotation_custom(g1, xmin=1, xmax=3, ymin=1, ymax=3) +
  annotation_custom(g2, xmin=7, xmax=9, ymin=7, ymax=9) +  
  geom_point()

1
结果的图片会很棒。 - Saren Tasciyan

7

DL Miller提供了另一种解决方案,使用ggproto()https://github.com/dill/emoGG

library(ggplot2)
library(grid)
library(EBImage)
img <- readImage(system.file("img", "Rlogo.png", package = "png"))
RlogoGrob <- function(x, y, size, img) {
    rasterGrob(x = x, y = y, image = img, default.units = "native", height = size, 
        width = size)
}

GeomRlogo <- ggproto("GeomRlogo", Geom, draw_panel = function(data, panel_scales, 
    coord, img, na.rm = FALSE) {
    coords <- coord$transform(data, panel_scales)
    ggplot2:::ggname("geom_Rlogo", RlogoGrob(coords$x, coords$y, coords$size, 
        img))
}, non_missing_aes = c("Rlogo", "size"), required_aes = c("x", "y"), default_aes = aes(size = 0.05), 
    icon = function(.) {
    }, desc_params = list(), seealso = list(geom_point = GeomPoint$desc), 
    examples = function(.) {
    })

geom_Rlogo <- function(mapping = NULL, data = NULL, stat = "identity", 
    position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, 
    ...) {
    layer(data = data, mapping = mapping, stat = stat, geom = GeomRlogo, 
        position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
        params = list(na.rm = na.rm, img = img, ...))
}
ggplot(mtcars, aes(wt, mpg))+geom_Rlogo()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接