Modify bin labels histogram

╄→гoц情女王★ 提交于 2019-12-12 19:18:22

问题


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?


回答1:


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=' - '))



来源:https://stackoverflow.com/questions/25037210/modify-bin-labels-histogram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!