Skip to content

Instantly share code, notes, and snippets.

@Steven-N-Hart
Created August 24, 2016 15:31
Show Gist options
  • Save Steven-N-Hart/a9aabb358681b0ff15e9537d46ce2bde to your computer and use it in GitHub Desktop.
Save Steven-N-Hart/a9aabb358681b0ff15e9537d46ce2bde to your computer and use it in GitHub Desktop.
Plot overlapping ggplots
#Plot any ggplot with 2 y-axes
#p1 and p2 are any plot objects from ggplot
ggplot_doubleY = function(p1,p2){
#Plot any ggplot with 2 y-axes
library(ggplot2)
library(gtable)
library(grid)
p2 = p2 + theme_bw() %+replace% theme(panel.background = element_rect(fill = NA))
grid.newpage()
# two plots
# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))
# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,
pp$l, pp$b, pp$l)
# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)
# draw it
grid.draw(g)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment