0

I have these combined histograms:

set.seed(1)
x <- rbind(data.frame(data = rnorm(500, -1, 1), group = 'First'),
           data.frame(data = rnorm(500, 1, 1), group = 'Second'))
ggplot(x, aes(data, fill=group)) +
  geom_histogram(alpha = 0.5, aes(y=(100*..count..)/sum(..count..)), color='black', position='identity')

In the plot, I would like to manually color the first group as red and the second group as green. I looked here, here, and here, but these did not answer my question.

Forklift17
  • 2,245
  • 3
  • 20
  • 32
  • 3
    Add `+ scale_fill_manual(values = c('red', 'green'))` to your plot – Allan Cameron Aug 28 '23 at 15:57
  • 2
    I suggest you used a named vector, perhaps `values=c(First="red", Second="green")`, as it removes ambiguity. While not a factor here, realize that the order that you provide and the order ggplot uses internally may not be the same (alphabetic sorting versus factors, for instance); if you do not name them, then it is possible that the colors are assigned to the incorrect groups. This might be obviously wrong in some circumstances but seems an unnecessary risk. @AllanCameron – r2evans Aug 28 '23 at 15:59
  • 1
    What exactly did you try to change the colors that didn't work? – MrFlick Aug 28 '23 at 16:09

1 Answers1

1

A few things to add/consider here:

  1. ggplot2 is recommending after_stat(.) instead of ..count..;
  2. Add color=group inside your aes(..) call, and you may also want fill= (which works here so long as you keep alpha=0.5; and
  3. Use a named vector of colors in a call to scale_*_manual.

First, using after_stat(count) and color=group only:

ggplot(x, aes(data, fill=group)) +
  geom_histogram(alpha = 0.5,
    aes(y=(100*after_stat(count))/sum(after_stat(count)), color=group, fill=group),
    position='identity') +
  scale_color_manual(values=c(First="red", Second="green"))

ggplot with color aesthetic by group

Same thing but including fill= and scale_fill_manual (and pre-defining the named vector of colors):

mycolors <- c(First="red", Second="green")
ggplot(x, aes(data, fill=group)) +
  geom_histogram(alpha = 0.5,
    aes(y=(100*after_stat(count))/sum(after_stat(count)), color=group, fill=group),
    position='identity') +
  scale_color_manual(values=mycolors) +
  scale_fill_manual(values=mycolors)

ggplot with color and fill aesthetics by group

r2evans
  • 141,215
  • 6
  • 77
  • 149