andrewj
andrewj

Reputation: 3035

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).

Upvotes: 11

Views: 16194

Answers (3)

Mapache
Mapache

Reputation: 33

If you don't want to call barplot() twice (per @MichaelChirico's comment), you can first call a new graphics frame with the appropriate dimensions instead of plotting a "blank" barplot (as suggested by @thelatemail):

# Simulate data
set.seed(123)
data <- sample(1:100, replace=T, prob=dnorm(1:100,50,3))

# Create blank frame
plot.new()
plot.window(
  xlim = c(0,(max(data)-min(data))+1),
  ylim = c(0,max(table(data)))
)

# Draw lines behind barplot first
abline(
  h=seq(0,max(table(data)),2),
  col="grey",lty="dashed")
  
barplot(
    table(factor(data,levels=min(data):max(data))),
    col = rainbow((max(data)-min(data))*2.5),
    space = 0,
    add = T)

barplot_with_lines_behind

Upvotes: 1

thelatemail
thelatemail

Reputation: 93833

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

Upvotes: 15

mavam
mavam

Reputation: 12552

If you use ggplot2, you don't have to worry about this. Your problem boils down to the geom order:

ggplot(data.frame(x=1:4, y=y), aes(x=x, y=y)) + 
    geom_bar(stat="identity") + 
    geom_hline(yintercept=mean(y), color="red")

line in front

In comparison:

ggplot(data.frame(x=1:4, y=y), aes(x=x, y=y)) + 
    geom_hline(yintercept=mean(y), color="red") +
    geom_bar(stat="identity")

line behind

Upvotes: 9

Related Questions