batcatcher
batcatcher

Reputation: 33

Adding lines to graph created using plotrix library

I have created a stacked histogram using the multhist function in the plotrix library, but I am unable to add a straight line to this histogram. Code that I would normally use doesn't seem to work in this setting.

Here's an example. I am trying to add the mean and standard errors of the overall distribution as simple vertical lines on the histogram, but these do not work properly. What am I doing wrong?

library(plotrix)

test1<-rnorm(30,0)
test2<-rnorm(30,0)
test3<-rnorm(30,0)

forstats<-c(test1,test2,test3)
mn<-mean(forstats)
se<-std.error(forstats)

together<-list(test1,test2,test3)
multhist(together, col=c(7,4,2), space=c(0,0), beside=FALSE,right=FALSE)

abline(v=mn)
abline(v=mn+se)
abline(v=mn-se)

Upvotes: 1

Views: 283

Answers (1)

jbaums
jbaums

Reputation: 27388

multhist uses barplot, so, as @BenBolker mentions here, the x-axis corresponds to bin index. It's a bit tricky to convert between native coordinates and bin index units, so I've put together another function for stacked histograms (for frequencies, anyway):

histstack <- function(x, breaks, col=rainbow(length(x)), ...) {
  col <- rev(col)
  if (length(breaks)==1) {
    rng <- range(pretty(range(x)))
    breaks <- seq(rng[1], rng[2], length.out=breaks)
  }
  h <- lapply(x, hist, plot=FALSE, breaks=breaks)
  cumcounts <- apply(sapply(h, '[[', 'counts'), 1, cumsum)

  for(i in seq_along(h)) {
    h[[i]]$counts <- cumcounts[nrow(cumcounts) - i + 1, ]
  }
  max_cnt <- max(sapply(h, '[[', 'counts'))
  plot(h[[1]], xlim=range(sapply(h, '[', 'breaks')), yaxt='n',
       ylim=c(0, max(pretty(max_cnt))), col=col[1], ...)
  sapply(seq_along(h)[-1], function(i) plot(h[[i]], col=col[i], add=TRUE, ...))
  axis(2, at=pretty(c(0, max_cnt)), labels=pretty(c(0, max_cnt)), ...)  
}

And here it is:

histstack(together, seq(-3, 3, 0.5), col=c(7, 4, 2), main='', 
          las=1, xlab='', ylab='')

abline(v=c(mn, mn+se, mn-se), lwd=2, )

enter image description here

IMO the x-axis labelling is probably more appropriate than that of multhist, since multhist implies that counts relate to the mid-bin values, whereas above it's clear that the x-axis ticks delineate the bins.

Upvotes: 1

Related Questions