Skip to content

Instantly share code, notes, and snippets.

@brodieG
Last active December 4, 2019 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brodieG/1bd57066b4d8930912215261394a9800 to your computer and use it in GitHub Desktop.
Save brodieG/1bd57066b4d8930912215261394a9800 to your computer and use it in GitHub Desktop.
Device Size for coord_fixed Ggplot
# Compute Device Size To Fully Fill With Plot
#
# This is not tested extensively and I know very little about messing with
# grid.
#
# GPL-2
#
# @param gtable e.g. as produced by `ggplotGrob(ggplot() ...)`
# @param din device dimension in inches, ideally use defaults to avoid
# calculation issues with npc units.
# @return numeric(2) containing width and height of device that would be fully
# occupied by provided gtable when rendered.
gtable_dim <- function(gtable, din=par()[['din']]) {
gw <- gtable::gtable_width(gtable)
gh <- gtable::gtable_height(gtable)
wunits <- attr(gw$arg1, 'unit')
wknown <- Reduce('+', grid::convertX(gw$arg1[wunits != 'null'], 'inches'))
wnull <- Reduce('+', gw$arg1[wunits == 'null'])
hunits <- attr(gh$arg1, 'unit')
hknown <- Reduce('+', grid::convertX(gh$arg1[hunits != 'null'], 'inches'))
hnull <- Reduce('+', gh$arg1[hunits == 'null'])
null.size <- min(c((din[1] - wknown) / wnull, (din[2] - hknown) / hnull))
c(wknown + null.size * wnull, hknown + null.size * hnull)
}
# Usage example
set.seed(1221)
dev.new(width=5, height=5)
dat <- data.frame(x=rnorm(100), y=rnorm(100), type=rep(1:2, each=50))
p <- ggplot(dat) + geom_point(aes(x, y)) +
facet_wrap(~type) + coord_fixed() +
theme(plot.background = element_rect(fill='red'))
print(p, new.page=FALSE)
dim <- gtable_dim(ggplotGrob(p))
dev.new(width=dim[1], height=dim[2])
p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment