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

Math122
  • 147
  • 1
  • 8
  • 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? – MrFlick May 14 '21 at 17:51

1 Answers1

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

Till
  • 3,845
  • 1
  • 11
  • 18
  • 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) – Math122 May 14 '21 at 18:19
  • 2
    I added in a line to change the colors with `scale_fill_manual(values = c("blue", "orange"))`. See [here](https://stackoverflow.com/questions/44889334/adding-space-between-my-geom-histogram-bars-not-barplot) for strategies do separate the bars. Also the [ggplot2 documentation and materials](https://ggplot2.tidyverse.org/index.html) are very helpful. – Till May 14 '21 at 18:29