Skip to content

Instantly share code, notes, and snippets.

@baptiste
Last active June 25, 2018 22:41
Show Gist options
  • Save baptiste/23c08d0b143a2c69fe641e17114d1b5a to your computer and use it in GitHub Desktop.
Save baptiste/23c08d0b143a2c69fe641e17114d1b5a to your computer and use it in GitHub Desktop.
justifying tables with annotation_custom
library(ggplot2)
library(egg)
library(gridExtra)
library(grid)
justify <- function(x, hjust="center", vjust="center", draw=FALSE){
w <- sum(x$widths)
h <- sum(x$heights)
xj <- switch(hjust,
center = 0.5,
left = 0.5*w,
right=unit(1,"npc") - 0.5*w)
yj <- switch(vjust,
center = 0.5,
bottom = 0.5*h,
top=unit(1,"npc") - 0.5*h)
x$vp <- viewport(x=xj, y=yj)
if(draw) grid.draw(x)
return(x)
}
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
tg <- tableGrob(mpg[1:3,2:3])
p + annotation_custom(grobTree(justify(tg, "right", "top")))
p2 <- p + facet_grid(. ~ cyl)
ltg <- plyr::dlply(mpg, "cyl", function(d) grobTree(justify(tableGrob(d[1:3,3:5]), "right", "top")))
dummy <- cbind(attr(ltg,"split_labels"), I(ltg))
p2 + geom_custom(data = dummy, aes(0,0,data=ltg), grob_fun = identity)
@baptiste
Copy link
Author

screen shot 2018-06-26 at 10 38 04 am

screen shot 2018-06-26 at 10 37 27 am

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