Skip to content

Instantly share code, notes, and snippets.

@johnDorian
Created December 1, 2014 15:42
Show Gist options
  • Save johnDorian/ac3694cc3c56f2fb9ee1 to your computer and use it in GitHub Desktop.
Save johnDorian/ac3694cc3c56f2fb9ee1 to your computer and use it in GitHub Desktop.
Function to plot secondary axis in ggplot2
library(ggplot2)
library(gtable)
library(grid)
library(ggthemes)
# extract gtable
ggplot_second_axis <- function(p1, p2){
p2 <- p2 + theme() %+replace%
theme(panel.background = element_rect(fill = NA))
grid.newpage()
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)
ia2 <- which(g2$layout$name == "ylab")
ga2 <- g2$grobs[[ia2]]
ga2$rot <- 90
g <- gtable_add_cols(g, g2$widths[g2$layout[ia2, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ga2, pp$t, length(g$widths) - 1, pp$b)
return(g)
}
# two plots
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue")
p2 <- ggplot(mtcars, aes(mpg, drat)) + geom_line(colour = "red")
f <- ggplot_second_axis(p1,p2)
grid.draw(f)
@dainiuxt
Copy link

dainiuxt commented Dec 6, 2016

Everything seemed to work OK until now, but from last month I get "Error in g2$grobs[[ia2]] :
attempt to select less than one element in get1index".
Changes in system: merged dplyr and data.table into dtplyr. Updated R to 3.3.2 from 3.3.1
Downgrade doesn't work. Any ideas? Thanks a lot.

@scipionesarlo
Copy link

I've the same problem. How to solve it?
Many thanks

@xinzhu0
Copy link

xinzhu0 commented Mar 21, 2022

There is a small error in line 34.
change
'ia2 <- which(g2$layout$name == "ylab")'
to
'ia2 <- which(g2$layout$name == "ylab-l")'

You should get the right plot.

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