0

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)
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
TCS
  • 1
  • http://stackoverflow.com/questions/26727741/how-to-show-a-legend-on-dual-y-axis-ggplot – user20650 Jun 19 '15 at 00:21
  • To label the axis, look for "Add axis titles" towards the bottom of [this answer](http://stackoverflow.com/questions/30126939/is-there-a-way-to-have-a-barplot-and-a-stacked-barplot-on-the-same-graph-using-b/30157977#30157977). – Sandy Muspratt Jun 19 '15 at 00:33
  • That is, grab the right axis title using: `RightAxisText <- g2$grobs[[which(g2$layout$name == "ylab")]]` Position the right axis title using: `g <- gtable_add_cols(g, unit.c(unit(1, "grobwidth", RightAxisText) + unit(1, "line")), pp$r+1)` and `g <- gtable_add_grob(g, RightAxisText, pp$t, pp$r+2)` – Sandy Muspratt Jun 19 '15 at 01:07

0 Answers0