R 中的直方图 (ggplot) - binwidth 不起作用

Histogram (ggplot) in R - binwidth not working

嘿,我有以下代码:

df = data.frame(X = rnorm(40), Y = rep(c("A", "B"), 20))
ggplot() + geom_histogram(data = df, aes(x = X, fill = factor(Y)), stat = "count", position = "dodge", bins = 5) + theme_bw()

我的目标是将 X 分成 5 个 bin 并绘制直方图,我们将在直方图上看到每个 bin 中 "A""B" 的数量。为什么此代码不起作用,我应该更改什么?因为 bins 不起作用 :(

不要使用 stat = "count"

library(ggplot2)
df = data.frame(X = rnorm(40), Y = rep(c("A", "B"), 20))
ggplot() +
  geom_histogram(
    data = df,
    aes(x = X, fill = factor(Y)),
    #stat = "count",
    position = "dodge",
    bins = 5
  ) +
  scale_fill_manual(values = c("blue", "orange")) +
  theme_bw()