Skip to content

Instantly share code, notes, and snippets.

@baptiste
Last active December 4, 2019 19:26
Show Gist options
  • Save baptiste/1a82a9d233178de7224b6b6d2cc779f3 to your computer and use it in GitHub Desktop.
Save baptiste/1a82a9d233178de7224b6b6d2cc779f3 to your computer and use it in GitHub Desktop.
library(ggplot2)
set.seed(1221)
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'))
# inspired by
# egg::set_panel_size
g <- ggplotGrob(p)
panels <- grep("panel", g$layout$name)
panel_index_w <- unique(g$layout$l[panels])
panel_index_h <- unique(g$layout$t[panels])
nw <- length(panel_index_w)
nh <- length(panel_index_h)
pw <- g$widths[panel_index_w]
ph <- g$heights[panel_index_h]
ar <- unlist(pw)[[1]] / unlist(ph)[[1]]
library(grid)
margin <- unit(0.5, 'in')
device_width <- unit(7, 'in')
# take out the non-null units (panels)
panel_width_in <- convertWidth(device_width - margin - sum(g$widths),
unitTo = "in", valueOnly = FALSE)
g$widths[panel_index_w] <- 1/nw*panel_width_in
# now set the panel height accordingly
g$heights[panel_index_h] <- 1/ar/nw * panel_width_in
device_height <- convertHeight(sum(g$heights) + margin, unitTo = "in")
ggsave('test.pdf', g,
width = device_width,
height = device_height)
@baptiste
Copy link
Author

baptiste commented Dec 4, 2019

Screen Shot 2019-12-05 at 8 25 32 AM

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