rplot

plot line behind barplot


I would like to create a barplot where the bars are plotted on top of the horizontal line.

The following code accomplishes this:

y <- c(1,2,3,5)
barplot(y)
abline(h=mean(y))
barplot(y, add=T)

However, I'm concerned that the add=T parameter in barplot(), if used repeatedly, can introduce printing artifacts. I'm curious if there's an alternative to the above code (though the above code may be the fastest method).


Solution

  • You could just plot nothing in your first call:

    y <- c(1,2,3,5)
    barplot(
      rep(NA, length(y)),
      ylim = pmax(range(y), 0),
      axes = FALSE
    )
    abline(h = mean(y))
    barplot(y, add = TRUE)
    

    Barplot with horizontal line behind the bars, as desired