Add legend category to ggplot2 line plot with two y-axes

665 views Asked by At

I'm trying to make a graph using ggplot2 with 2 different y-axes (appropriate and not misleading, I promise).

I've got a legend for the first graph, but I can't seem to be able to add one for the second. Nor can I label this axis.

My code is quite long-winded so I've abbreviated the coding of p1 as I don't think that I need to change that.

p1 <- p + theme(legend.position = "top")    
p2 <- ggplot(concB.only.for.R, aes(ConcB.ml, ConcB))     
        geom_line(colour = "#000099") + theme_bw() +
        theme(panel.background = element_rect(fill = NA)) +
        theme(legend.position = "top")
g1 <- ggplot_gtable(ggplot_build(p1))    
g2 <- ggplot_gtable(ggplot_build(p2))     
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)     
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)     
grid.draw(g)
0

There are 0 answers