28

I know that this question has been asked before but the solutions don't seem to work for me.

What I want to do is represent my median, mean, upper and lower quantiles on a histogram in different colours and then add a legend to the plot. This is what I have so far and I have tried to use scale_color_manual and scale_color_identity to give me a legend. Nothing seems to be working.

quantile_1 <- quantile(sf$Unit.Sales, prob = 0.25)
quantile_2 <- quantile(sf$Unit.Sales, prob = 0.75)

ggplot(aes(x = Unit.Sales), data = sf) + 
  geom_histogram(color = 'black', fill = NA) + 
  geom_vline(aes(xintercept=median(Unit.Sales)),
            color="blue", linetype="dashed", size=1) + 
  geom_vline(aes(xintercept=mean(Unit.Sales)),
            color="red", linetype="dashed", size=1) +
  geom_vline(aes(xintercept=quantile_1), color="yellow", linetype="dashed", size=1)

resulting plot

Roland
  • 127,288
  • 10
  • 191
  • 288
Preet Rajdeo
  • 377
  • 1
  • 5
  • 11

1 Answers1

51

You need to map the color inside the aes:

ggplot(aes(x = Sepal.Length), data = iris) + 
  geom_histogram(color = 'black', fill = NA) + 
  geom_vline(aes(xintercept=median(iris$Sepal.Length),
                 color="median"), linetype="dashed",
             size=1) +
  geom_vline(aes(xintercept=mean(iris$Sepal.Length),
                 color="mean"), linetype="dashed",
             size=1) +
  scale_color_manual(name = "statistics", values = c(median = "blue", mean = "red"))

resulting plot

Roland
  • 127,288
  • 10
  • 191
  • 288
  • 1
    If this does not work for you: For me it worked by adding "show_guide=TRUE" to one of the geom_vline commands. – panuffel Sep 19 '17 at 11:43
  • 2
    Didn't work for me even after I changed "show_guide" to "show.legend" (when R complained) and adding it to each of my 'geom_vlines'. – Nate Lockwood Jun 18 '19 at 18:24
  • 4
    You have probably written your colour outside of the aes(). No need for "show_guide" or "show.legend". Your "color=" needs to be IN the "aes()". – TeYaP Mar 18 '20 at 15:08