[R] bar plot/ histogram

Marc Schwartz marc_schwartz at comcast.net
Wed Feb 11 19:24:58 CET 2009


on 02/11/2009 12:10 PM phoebe kong wrote:
> 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

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)

> table(data)
data
 1  2  3  4  5  6  7  8  9 10
 7  6 11 14 14  5 11 15 11  6

> cut(data, breaks = c(0:4, Inf), labels = c(1:4, ">=5"))
  [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

> table(cut(data, breaks = c(0:4, Inf), labels = c(1: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




More information about the R-help mailing list