colin
colin

Reputation: 2666

adding grouping lines to a barplot in R

I created a barplot using the follow code:

#create function for plotting error  bars
errb <- function (x, y, ebl, ebu = ebl, length = 0.08, ...){
  arrows(x, y + ebu, x, y - ebl, angle = 90, code = 3,
         length = length, ...)
}

#generate plot data
means <- c(0.976,0.664, 1.12, 1.22)
errs  <- c(0.16, 0.17, 0.16, 0.16)

#plot labels
names <- c('+NaCl', '+NaCl',expression(paste('+NaNO'[3])),expression(paste('+H'[2]*'O')))

#plot
plot1<-barplot(means, beside=T,border=NA,
               ylim=c(0,1.6),
               names.arg=names)
errb(plot1,means,ebl=errs,ebu=errs)
box(bty="L")

It looks like this:

enter image description here

I'd like to add some labels in the top white space of the figure, to indicate whether or not the treatment E was present. The first bar is (-E) and bars 2-4 are (+E). I'd like the outcome to look like this drawing: enter image description here

How can I go about doing this in base R?

Upvotes: 2

Views: 54

Answers (1)

gung - Reinstate Monica
gung - Reinstate Monica

Reputation: 11893

You just need to use text() and arrows(). Consider:

text(x=0.7, y=1.5, labels="(-E)", adj=c(.5,.5))
text(x=3.1, y=1.5, labels="(+E)", adj=c(.5,.5))
arrows(x0=1.4, x1=2.9, y0=1.5, code=1, angle=90, length=.1)
arrows(x0=3.3, x1=4.8, y0=1.5, code=2, angle=90, length=.1)

enter image description here

Upvotes: 1

Related Questions