Skip to content

Instantly share code, notes, and snippets.

@mikmart
Last active September 13, 2018 07:24
Show Gist options
  • Save mikmart/b7a2e647e1ff5b6e7de3843d468f7e40 to your computer and use it in GitHub Desktop.
Save mikmart/b7a2e647e1ff5b6e7de3843d468f7e40 to your computer and use it in GitHub Desktop.
library(ggplot2)
library(magick)
#> Linking to ImageMagick 6.9.9.14
#> Enabled features: cairo, freetype, fftw, ghostscript, lcms, pango, rsvg, webp
#> Disabled features: fontconfig, x11

library(grid)
library(gtable)

p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + theme_bw()
  
gt <- ggplotGrob(p)

panel <- subset(gt$layout, name == "panel")
ypos <- sum(tail(gt$heights, -panel$b)) # space below panel

lw <- sum(head(gt$widths, panel$l - 1)) # space left of panel
rw <- sum(tail(gt$widths, -panel$r))    # space right of panel

lerp <- function(t, a, b) a + t * (b - a)
xpos <- lerp(0.01, lw, unit(1, "npc") - rw)

g <- image_read("White_bg.png") %>%
  rasterGrob(x = xpos, y = ypos, hjust = 0, height = unit(1, "line"))

p
grid.draw(g)

Created on 2018-09-12 by the reprex package (v0.2.0.9000).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment