Skip to content

bar plot/ histogram

3 messages · phoebe kong, Marc Schwartz, Greg Snow

#
Hi all,

I would like to construct plot of the distribution of N, where N range
from 1 to 10. I couldn't just use the hist(), as I want the categories
for the bars are: 1, 2, 3, 4, >=5. So this will be a bar plot with 5
bars, and the height of the bar will be the frequency of N. (eg bar#1
will be the frequency of N=1, bar #2 will be frequency of N=2, and
bar#5 will be the frequency of N>=5).

Thanks in advance for your help!

SY
#
on 02/11/2009 12:10 PM phoebe kong wrote:
You can use cut() to break up your data into the desired groupings and
then use barplot().

set.seed(1)

data <- sample(10, 100, replace = TRUE)
data
 1  2  3  4  5  6  7  8  9 10
 7  6 11 14 14  5 11 15 11  6
[1] 3   4   >=5 >=5 3   >=5 >=5 >=5 >=5 1   3   2   >=5 4   >=5 >=5
 [17] >=5 >=5 4   >=5 >=5 3   >=5 2   3   4   1   4   >=5 4   >=5 >=5
 [33] >=5 2   >=5 >=5 >=5 2   >=5 >=5 >=5 >=5 >=5 >=5 >=5 >=5 1   >=5
 [49] >=5 >=5 >=5 >=5 >=5 3   1   1   4   >=5 >=5 >=5 >=5 3   >=5 4
 [65] >=5 3   >=5 >=5 1   >=5 4   >=5 4   4   >=5 >=5 >=5 4   >=5 >=5
 [81] >=5 >=5 4   4   >=5 3   >=5 2   3   2   3   1   >=5 >=5 >=5 >=5
 [97] >=5 >=5 >=5 >=5
Levels: 1 2 3 4 >=5
1   2   3   4 >=5
  7   6  11  14  62


barplot(table(cut(data, breaks = c(0:4, Inf), labels = c(1:4, ">=5"))))


See ?cut for more information.

HTH,

Marc Schwartz
#
You can still use hist, just provide your own breaks:

mydata <- sample(1:10, 100, TRUE, 10:1)
br <- c( 0.5:4.5, 10.5 )
hist(mydata, breaks=br, xaxt='n')
axis(1, at= c(1:4, mean(5:10)), c( 1:4, '5-10'))
box(bty='l')

hope this helps,