Last active
June 25, 2018 22:41
-
-
Save baptiste/23c08d0b143a2c69fe641e17114d1b5a to your computer and use it in GitHub Desktop.
justifying tables with annotation_custom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Author
baptiste
commented
Jun 25, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment