21
votes

I'd like to feed geom_histogram the number of bins for my histogram instead of controlling bins through binwidth. The documentation says I can do this by setting the bins argument. But when I run

ggplot(data = iris, aes(x = Sepal.Length)) + stat_bin(bins = 5)

I get an output message with 30 bins, as if I didn't specify binwidth at all.

stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

I've tried feeding this argument to stat_bin and qplot with the same problem. Am I doing something wrong?

I'm using ggplot2 version 1.0.1.

1
can you share your data pleasemtoto
What version of ggplot are you using?Heroka
If you update to ggplot 2.0 the stat_bin(bins = x) command should work.bouncyball
works for me. consider updating ggplot and/or restarting your r session.mtoto
It works fine for me, but oddly: it always produces one more bin than I specify. An index-0 bug? (ggplot 2.0.0)alistaire

1 Answers

43
votes

Just pass bins=x directly

library(ggplot2)
df <- data.frame(a = rnorm(10000))

ggplot(df, aes(x=a)) + geom_histogram()

Produces this (with warning "stat_bin() using bins = 30. Pick better value with binwidth."):

enter image description here

And this:

ggplot(df, aes(x=a)) + geom_histogram(bins=10)

Produces:

enter image description here

Using ggplot2 version 2.0.0