how to show a legend on dual y-axis ggplot

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)

enter image description here

Leave a Comment