Skip to content

Instantly share code, notes, and snippets.

@baptiste
Last active December 20, 2015 13:49
Show Gist options
  • Save baptiste/6141590 to your computer and use it in GitHub Desktop.
Save baptiste/6141590 to your computer and use it in GitHub Desktop.
double axis hack in ggplot2
library(gtable)
library(ggplot2)
library(plyr)
set.seed(1)
d <- data.frame(x=rep(1:10, 5),
y=rnorm(50),
g = gl(5,10))
# example plot
p <- ggplot(d, aes(x,y,colour=g)) +
geom_line() +
scale_x_continuous(expand=c(0,0))
g <- ggplotGrob(p)
# extract the axis only, we don't need the rest
gl <- gtable_filter(ggplotGrob(p), "axis-l")
# messing around with the axis...
gl$grobs[[1]][["children"]]["axis"][[1]][["grobs"]][[1]] <- nullGrob()
w <- gl$grobs[[1]][["children"]]["axis"][[1]][["widths"]][[2]] - unit(0.1, "cm")
gl$grobs[[1]][["children"]]["axis"][[1]][["widths"]][[2]] <- w
gl$grobs[[1]][["children"]]["axis"][[1]][["widths"]][[1]] <- unit(0,"line")
# add a cell next to the main plot panel, and insert gl there
index <- subset(g$layout, name == "panel")
g <- gtable_add_cols(g, w, pos=index$r)
g <- gtable_add_grob(g, gl, t = index$t, l=index$r+1,
b=index$b, r=index$r+1)
grid.newpage()
grid.draw(g)
@baptiste
Copy link
Author

baptiste commented Aug 6, 2013

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