Modify bin labels histogram
-
21-12-2019 - |
Question
I made the following histogram:
one <- c(2,2,3,3,3,3,4,4,4,4,4,4,5,5,5,5,6,6,7,8)
hist(one, breaks = 3)
Instead of a range from 2-8 on the x-axis, I need three labels on the x-axis that summarize the range of values like this: 2-3; 4-5; 6-8
How can I modify the code for the x-axis to get just three labels, and in the correct location?
Solution
It's easy to label midpoints for the ranges using:
h <- hist(one, breaks = 3, xaxt = 'n')
axis(1, h$mids, h$mids)
But if you want to have the labels be character strings naming the ranges, you have to do a little more work. Take a look at str(h)
to see what you have to work with:
> str(h)
List of 6
$ breaks : num [1:4] 2 4 6 8
$ counts : int [1:3] 12 6 2
$ density : num [1:3] 0.3 0.15 0.05
$ mids : num [1:3] 3 5 7
$ xname : chr "one"
$ equidist: logi TRUE
- attr(*, "class")= chr "histogram"
You can use the breaks
element to construct axis labels:
h <- hist(one, breaks = 3, xaxt = 'n')
axis(1, h$mids, paste(h$breaks[1:3], h$breaks[2:4], sep=' - '))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow