1

The most popular (and simplest) way to adding image to the ggplot2 graph is annotation_custom:

library(ggplot2)
library(png)
library(grid)

img <- readPNG(system.file("img", "Rlogo.png", package="png"), TRUE)
gpp <- rasterGrob(img, interpolate=TRUE)
gpp$width <- unit(1, "npc") 
    gpp$height <- unit(1, "npc")
df <- data.frame(x=seq(1,2,0.01),y=seq(1,2,0.01))
ggplot(df,aes(x=x,y=y)) + 
    annotation_custom(gpp, xmin=1, xmax=2.5, ymin=1, ymax=1.5) +
    geom_point()

In this way, image will be placed over the scale grid.

How to place image under the grid, but with bindings to the coords, not to the borders of the plot?

Stanislav Ivanov
  • 1,854
  • 1
  • 16
  • 22
  • 2
    You mean like `p <- ggplot(df,aes(x=x,y=y))+ theme(plot.margin = unit(c(1,1,8,1), "lines")) + annotation_custom(gpp, xmin=.9, xmax=1.1, ymin=.7, ymax=.9); gt <- ggplot_gtable(ggplot_build(p)); gt$layout$clip[gt$layout$name == "panel"] <- "off"; grid.draw(gt)`? There are numerous examples on SO. – lukeA Dec 03 '15 at 17:45
  • `+ theme(panel.ontop=TRUE)` in dev version – baptiste Dec 03 '15 at 20:38
  • `gt$layout$clip[gt$layout$name == "panel"] <- "off";` did not change anything, but `theme(panel.ontop=TRUE, panel.background = element_rect(colour = NA,fill="transparent"))` in _dev_ version working as required. Thanks! Is it possible to get this behavior in the stable ggplot? – Stanislav Ivanov Dec 04 '15 at 13:35

1 Answers1

2

It's possible in the development version of ggplot2.

How to install it see this answer: https://stackoverflow.com/a/9656182/4265407

Minimal working example:

library(devtools)
dev_mode(on=T)

library(ggplot2)
library(png)
library(grid)

img <- readPNG(system.file("img", "Rlogo.png", package="png"), TRUE)
gpp <- rasterGrob(img, interpolate=TRUE)
gpp$width <- unit(1, "npc") 
gpp$height <- unit(1, "npc")
df <- data.frame(x=seq(1,2,0.01),y=seq(1,2,0.01))
ggplot(df,aes(x=x,y=y)) + 
    annotation_custom(gpp, xmin=1, xmax=2.5, ymin=1, ymax=1.5) +
    geom_point() + theme(panel.ontop=TRUE,
    panel.background = element_rect(colour = NA,fill="transparent"))
Community
  • 1
  • 1
Stanislav Ivanov
  • 1,854
  • 1
  • 16
  • 22