Search code examples
rggplot2axisgtable

Dual y axis - label and background gridlines of right y axis


I need to make a dual y axis in ggplot2. I have tried to follow @kohske solution published here: http://rpubs.com/kohske/dual_axis_in_ggplot2 However, two things are still undesired and I can't figure out how to solve them. 1. In the plot below the label of right y axis is absent, while I want to make it present 2. gridlines for right y axis is shown on top of bar plot, while it should be in the background. Here's the plot:

enter image description here

and the code:

library(ggplot2)
library(grid)
library(gtable)

grid.newpage()
p1 <- ggplot(ex, 
         aes(factor(subgroups, levels = c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 
                                          'Saturday', 'Sunday')),
             y_left)) + 
  geom_bar(fill = rgb(16/255, 72/255, 128/255), stat = 'identity') + 
  theme_bw() +
  labs(x = 'weekday')
p2 <- ggplot(ex, aes(factor(subgroups,
                              levels = c('Monday', 'Tuesday', 'Wednesday', 
                                         'Thursday', 'Friday', 'Saturday', 'Sunday')), y_right)) + 
  geom_line(colour = rgb(237/255, 165/255, 6/255), group = 1) + 
  geom_point(color = rgb(237/255, 165/255, 6/255), size = 3) +
  scale_y_continuous(limits = c(0, 180)) +
  labs(y = 'name for y_left axis') +
  theme_bw() %+replace% 
  theme(panel.background = element_rect(fill = NA))
# extract gtable
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))

# overlap the panel of 2nd plot on that of 1st plot
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)

# axis tweaks
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)

# draw it
grid.draw(g)

Solution

  • They added a secondary axis option to ggplot a while back. Try putting both geoms on a single plot and adding scale_y_continuous(sec.axis = sec_axis(~.-280), name = "My Second Axis").

    Instead of simple subtraction, you can compute a ratio. This can be done inline, using something like sec.axis = sec_axis(~. * max(myData$y) / max(myData$y2)), or you can compute it ahead of time and apply it to both the 2nd axis and the data you intend to be read on the second axis, like this:

    library(ggplot2)
    # Create Sample Data
    myData <- data.frame(x = seq(1, 10, length.out = 10), 
                         y = seq(0, 20, length.out = 10), 
                         y2 = seq(0, 100, length.out = 10))
    myData.ratio <- max(myData$y) / max(myData$y2)
    ggplot(myData, (aes(x=x, y=y))) +
        geom_bar(stat="identity", aes(y=y2 * myData.ratio), fill = "lightblue") +
        geom_line(color="red") +
        geom_point(color="red") +
        scale_y_continuous(sec.axis = sec_axis(~. / myData.ratio, name = "My Second Axis"))
    

    Note that we're multiplying the actual values by the ratio in the geom and dividing by it when computing the axis.

    Output:

    Dual Axis Output