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))
CodePudding user response:
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)
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
CodePudding user response:
You can specify the breaks to be whatever you want with the breaks
parameter to the hist()
function. You should combine this with the freq = TRUE
parameter, or else you'll get a density plot, and the density at zero will be infinite. The plot doesn't look very good though, because the zero bin has no width:
hist(fish$num, breaks = c(0, 0, 5, 10, 15, 20), freq=TRUE)
I'm not sure what you'd want to do instead.