0

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

1
  • What do you have stat = "count"? That's interfereing with the default histogram stat. You are trying to create a dodged histogram? That's pretty ususaly. Do you really just want a dodged bar chart? Commented May 14, 2021 at 17:51

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! Could you tell me how to decrease width of the column (beacuse now there is no space between columns) and the color of columns (for example from red and green to blue and orange)
I added in a line to change the colors with scale_fill_manual(values = c("blue", "orange")). See here for strategies do separate the bars. Also the ggplot2 documentation and materials are very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.