[R] y-axis in histograms

Jim Lemon bitwrit at ozemail.com.au
Thu Nov 17 04:33:27 CET 2005


Michael Graber wrote:
> Dear R- list,
> I have some data to present with histograms. Therefore I used hist(...). 
> I have few values with almost 80% of
> the frequencies (totaly 800) and some other values with low frequencies 
> ( totaly 5 -10 )
> that I want to emphasize. Therefore I want to "cut" the y-axis on 100, 
> but I
> don't know how to deal with this.
> 
If you mean that you would like to have an axis break from 10 to 100, 
you can try this:

# be creative, make up some data
fakedat<-c(sample(1:6,50,TRUE),sample(7:9,1000,TRUE))
# get the histogram counts
# note that I have to explicitly specify breaks
fakehist<-hist(fakedat,breaks=0:10,type="n")
# here's a rough function
gap.barplot<-function(y,gap,x=NA,xlabels=NA,col=NULL,...) {
  if(missing(y) || missing(gap))
   stop("Must pass at least y and gap")
  littleones<-which(y<=gap[1])
  bigones<-which(y>=gap[2])
  if(length(bigones)+length(littleones) != length(y))
   warning("gap includes some values of y")
  gapsize<-gap[2]-gap[1]
  if(is.na(x)) x<-1:length(y)
  if(is.na(xlabels)) xlabels<-as.character(x)
  xlim<-range(x)
  ylim<-c(min(y),max(y)-gapsize)
  plot(0,xlim=xlim,ylim=ylim,axes=FALSE,type="n",...)
  box()
  axis(1,at=x,labels=xlabels)
  ytics<-pretty(y)
  littletics<-which(ytics<gap[1])
  bigtics<-which(ytics>=gap[2])
  axis(2,at=c(ytics[littletics],ytics[bigtics]-gapsize),
   labels=c(ytics[littletics],ytics[bigtics]))
  axis.break(2,gap[1])
  halfwidth<-min(diff(x))/2
  plot.lim<-par("usr")
  rect(x-halfwidth,plot.lim[3],x+halfwidth,
   c(y[littleones],y[bigones]-gapsize),
   col=col)
  abline(h=gap[1],col="white",lwd=5)
}
gap.barplot(fakehist$counts,gap=c(100,295))

Jim




More information about the R-help mailing list