Search code examples
rhistogram

Histogram in R with 1 bin for zeros only


Is it possible to make a histogram in R with bins of different sizes? I'm working with count data and the zeros need to have their own bin, but the other numbers can be binned into whatever would make sense. A single histogram for all fish counts is fine.

fish<-structure(list(num = c(0, 11, 1, 0, 
                             13, 11, 0, 1, 0, 0, 11, 11, 0, 10, 1, 0, 0, 0, 0, 0, 0, 0, 
                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 9, 0, 2, 1, 0, 
                             7, 6, 0, 4, 8, 0, 8, 6, 0)), 
                class = "data.frame", row.names = c(NA,-50L))

Solution

  • Use cut to have 0 on its own, then use seq to create bins:

    barplot(table(cut(fish$num, c(0, seq(1, 15, 3)), right = FALSE)), space = 0)
    

    enter image description here


    Edit: First bar only includes zeros, see:

    table(fish$num)
    # 0  1  2  4  6  7  8  9 10 11 13 
    #31  4  1  1  2  1  2  1  1  4  2 
    
    table(cut(fish$num, c(0, seq(1, 15, 3)), right = FALSE))
    #  [0,1)   [1,4)   [4,7)  [7,10) [10,13) 
    #     31       5       3       4       5