Centering values ​​on bars in a histogram in R

Looking for the x axis values ​​to be plotted in the center of the rods in R.

Having trouble finding a way to make this possible, the code below:

hist(sample_avg, breaks =7, ylim=c(0,2000), main = 'Histogram of Sample Average for 1 Coin Flip', xlab= 'Sample Average') 

This is easy for a flip coin, so I have 6 possible values ​​and you want to have 6 buckets with x-axis marks under each corresponding panel.

Any help is greatly appreciated.

+8
r
source share
3 answers

hist() returns the x coordinate of the midpoints of the columns in the mids components, so you can do this:

 sample_avg <- sample(size=10000,x=seq(1,6),replace=TRUE) foo <- hist(sample_avg, breaks =7, ylim=c(0,2000), main = 'Histogram of Sample Average for 1 Coin Flip', xlab= 'Sample Average', xaxt="n") axis(side=1,at=foo$mids,labels=seq(1,5)) 
+12
source share
 # when dealing with histogram of integers, # then adding some residual ~ 0.001 will fix it all... # example: v = c(-3,5,5,4,10,8,8) a = min(v) b = max(v) foo = hist(v+0.001,breaks=ba,xaxt="n",col="orange", panel.first=grid(),main="Histogram of v",xlab="v") axis(side=1,at=foo$mids,labels=seq(a,b)) 
+1
source share

Not as elegant as you might have hoped, but it’s best to use axes = F and then put your own axes with the β€œaxis” command, specifying the labels you want to see.

Link: https://stat.ethz.ch/pipermail/r-help/2008-June/164271.html

0
source share

All Articles