Math122
Math122

Reputation: 147

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

Upvotes: 0

Views: 973

Answers (1)

Till
Till

Reputation: 6628

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

Upvotes: 2

Related Questions