Search code examples
ggplot2tufte

In ggplot, how to make panel.grid.major on top of the barplot?


I wish to produce a graph panel grid lines which are overlaid on top of the figures. (I want to create an effect that is much like what is shown in Tufte).

enter image description here

I created this using geom_segment, but the drawback is that I need to set the heights at which the segments are manually – but I would like that to be set automatically at the height of the ticks.

df <- data.frame(id=1:5, val=abs(rnorm(5)))

ggplot(df, aes(id, val)) + geom_bar(stat="identity") + 
 theme_tufte() + 
 geom_segment(x=-Inf, y=0:4, xend=Inf, yend=0:4, color="white")

Solution

  • You can get the value of the tick break positions from layout$panel_params[[1]]$y.major_source. Then you can just use a horizontal line at those points. For your example it would look something like this:

    library(ggthemes)
    df <- data.frame(id=1:5, val=abs(rnorm(5)))
    
    myPlot <- ggplot() + geom_bar(data = df, aes(x = id, y = val), stat="identity") + 
      theme_tufte()
    
    myTuftePlot <- ggplot_build(myPlot)
    y.ticks <- myTuftePlot$layout$panel_params[[1]]$y.major_source
    myPlot + geom_hline(aes(yintercept = y.ticks), colour = 'white')