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)