Reputation: 1397
I'm getting crazy with hist() function. I have a dataset as follows:
table(data)
0 1 2 3 4 5 7 8
85 7 3 4 6 1 2 1
So I expect that hist(data, labels=TRUE)
returns me a histogram with 9 bins, one for the zeros, one for ones, etc. and with a value over each bin. But it aggregates the 0s and 1s and after one day of search on google, I still cannot figure out how I can fix it. I also tried to declare the number of bins like hist(data, breaks=c(0,8))
but nothing.
As an alternative, I tried with histogram
of the lattice
package, and it works fine... but I cannot figure out how to have the value of each bin displayed...
Can you help me either way (having the right number of columns with hist()
or having bins values displayed with histogram()
)?
thanks so much.
Upvotes: 5
Views: 8256
Reputation: 59385
hist(...)
uses right-closed intervals by default. You can change this using the right=...
argument.
x <- c(0, 1, 2, 3, 4, 5, 7, 8)
y <- c(85, 7, 3, 4, 6, 1, 2, 1)
z <- rep(x,times=y)
par(mfrow=c(1,2))
hist(z,right=T, main="Right closed")
hist(z,right=F, main="Left Closed")
Here's the equivalent in ggplot
, which IMO is a bit clearer.
library(ggplot2)
ggplot(data.frame(z), aes(x=factor(z))) +
geom_histogram(fill="lightgreen", color="grey50")
Upvotes: 5