Search code examples
rggplot2histogram

Histogram (ggplot) in R - binwidth not working


Hey I have the following code:

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()

My goal is to divide X into 5 bins and plot the histogram on which we will see the number of "A" and "B" in each bin. Why this code doesn't work and what should I change? Because bins doesnt work :(


Solution

  • Don't use 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()