ShortMyCDS
ShortMyCDS

Reputation: 123

Centering Values on Bars in Histogram in R

Looking to have the values of x-axis plotted in the center of the bars in R.

Having issues finding a way to make this possible, code is below:

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

This is just for a coin flip, so I have 6 possible values and want to have 6 buckets with the x-axis tick marks underneath each respective bar.

Any help is much appreciated.

Upvotes: 11

Views: 25633

Answers (3)

Eduardo Jacob
Eduardo Jacob

Reputation: 71

# 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=b-a,xaxt="n",col="orange",
panel.first=grid(),main="Histogram of v",xlab="v")
axis(side=1,at=foo$mids,labels=seq(a,b))

Upvotes: 4

Stephan Kolassa
Stephan Kolassa

Reputation: 8267

hist() returns the x coordinate of the midpoints of the bars 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))

Upvotes: 13

John McDonnell
John McDonnell

Reputation: 1490

Not as nifty as you might have been hoping, but looks like the best thing is to use axes=F, then put in your own axes with the 'axis' command, specifying the tick marks you want to see.

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

Upvotes: 0

Related Questions