Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom x-axis labels for hist()

I am using the code below to create a histogram. I've tried replacing the x-axis values using the axis code, but nothing happens other than my x-axis ends up with no labels. Does anyone have any solutions?

 par(mfrow=c(3,1))
 for (i in c(10,20,30)) {
   a <- rnorm(50, 90, i)
   hist(a, breaks=10, main = i, xaxt="n")
   axis(1,at=seq(-2,2,by=1/3), labels =seq(-2,2,by=1/3))
   abline(v=i * seq(-2, 2, by = 1/3) + 90, col = rainbow(length(seq(-2,2,by=1/3))))
  }
like image 632
john connor Avatar asked Nov 23 '25 11:11

john connor


1 Answers

You probably want a sequence in the range of the breaks with length of the length of your custom sequence. You may exploit the invisible return of hist.

set.seed(42)
op <- par(mfrow=c(3, 1))
for (i in c(10, 20, 30)) {
  a <- rnorm(50, 90, i)
  h <- hist(a, breaks=10, main=i, xaxt="n")
  sq <- round(seq(-2, 2, by=1/3), 2)
  ats <- do.call(seq, c(as.list(range(h$breaks)), length.out=length(sq)))
  axis(1, at=ats, labels=sq)
  abline(v=i * sq + 90, col=rainbow(length(sq)))
}
par(op)

Gives

enter image description here

like image 195
jay.sf Avatar answered Nov 26 '25 02:11

jay.sf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!