I am trying to compose a dual y-axis chart using ggplot. Firstly let me say that I am not looking for a discussion on the merits of whether or not it is good practice to do
Similar to the technique you use above you can extract the legends, bind them and then overwrite the plot legend with them.
So starting from # draw it
in your code
# extract legend
leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]
g$grobs[[which(g$layout$name == "guide-box")]] <-
gtable:::cbind_gtable(leg1, leg2, "first")
grid.draw(g)