Last active
December 20, 2015 13:49
-
-
Save baptiste/6141590 to your computer and use it in GitHub Desktop.
double axis hack in ggplot2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
same idea here: http://rpubs.com/kohske/dual_axis_in_ggplot2