将图像插入图表区域外的ggplot

时间:2012-09-17 16:42:55

标签: r ggplot2

是否可以将图像添加到图表区域外的ggplot图表中?

我知道可以使用annotate_raster和annotate_custom将图像添加到图表中,但是它们都会在图表中添加图像。我需要在图表上方的右上角添加公司徽标 - 在标题级别。

使用annotate_custom添加图片的示例: Inserting an image to ggplot2

更新:根据user1317221_G的建议,我可以将图片放在外面。

library(png)
library(grid)
library(ggplot2)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))

g <- rasterGrob(img, interpolate=TRUE)
plt <- qplot(1:10, 1:10, geom="blank") +
      opts(title = 'Title') + 
      geom_point() 
plt2 <- plt + annotation_custom(g, xmin=9, xmax=10, ymin=10.5, ymax=11.25)

gt <- ggplot_gtable(ggplot_build(plt2))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

我想自动放置图像 - 自动确定xmin / xmax和ymin / ymax。使用传统图形我可以调用par('usr')并获取图表参数,但这不适用于ggplot图表。有没有一种简单的方法来确定ggplot中的绘图区域?例如,获取plt的大小并将限制值插入plt2

UPDATE2:如果使用分面,此方法也不起作用。例如,我想在标题级别的右角放置徽标,如下图所示,如果我使用上述方法,我会收到错误。

d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) + 
     xlim(0, 2) + 
     stat_binhex(na.rm = TRUE) + 
     labs(title = 'Title') +
     theme(aspect.ratio = 1) + 
     facet_wrap(~ color, scales = "free_x")

0 个答案:

没有答案