直接在 ggplot 中设置直方图的 bin 数

Set number of bins for histogram directly in ggplot

我想为我的直方图提供 geom_histogram bins 的数量,而不是通过 binwidth 控制 bins。 The documentation 说我可以通过设置 bins 参数来做到这一点。但是当我 运行

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

我收到一条包含 30 个 bin 的输出消息,好像我根本没有指定 binwidth。

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

我试过将此参数提供给 stat_binqplot,但问题相同。我做错了什么吗?

我正在使用 ggplot2 版本 1.0.1。

直接传bins=x就可以了

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

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

生成这个(带有警告“stat_bin() 使用 bins = 30。使用 binwidth 选择更好的值。”):

还有这个:

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

产生:

使用 ggplot2 版本 2.0.0