【问题标题】:Display custom image as geom_point [duplicate]将自定义图像显示为 geom_point [重复]
【发布时间】:2014-12-24 13:10: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")) +

给出错误:

不知道如何为对象类型自动选择比例 原型/环境。默认为连续错误:美学必须 要么是长度一,要么与 dataProblems:(annotation_raster(conv_pic, xmin = 0, ymin = 0, xmax = 5, ymax = 5))

【问题讨论】:

标签: r ggplot2 ggproto


【解决方案1】:

point geom 是用来创建散点图的,它似乎并不能满足您的需要,即显示自定义图像。不过here回答了一个类似的问题,说明问题可以通过以下步骤解决:

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

(2) 使用rasterGrob()函数在给定的位置、大小和方向渲染光栅对象,

(3) 使用qplot()等绘图函数,

(4) 使用诸如annotation_custom() 之类的几何图形作为静态注释,指定用户20650 提到的x 和y 限制的粗略调整。

使用下面的代码,我可以在给定的 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()

【讨论】:

  • 一张结果图会很棒
【解决方案2】:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多