16

Have a problem of adding legend to different smooth in ggplot.

    library(splines)
    library(ggplot2)
    temp <- data.frame(x = rnorm(200, 20, 15), y = rnorm(200, 30, 8))

    ggplot(data = temp, aes(x, y)) + geom_point() + 
      geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), col='blue') + 
      geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), col='red')

I have two splines: red and blue. How I can add a legend for them?

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
R.Arkhipov
  • 235
  • 1
  • 2
  • 5

1 Answers1

31

Put the colour in aes() and add scale_colour_manual():

ggplot(data = temp, aes(x, y)) + geom_point() + 
  geom_smooth(method = 'lm', formula = y ~ bs(x, df=5, intercept = T), aes(colour="A")) + 
  geom_smooth(method = 'lm', formula = y ~ ns(x, df=2, intercept = T), aes(colour="B")) +
  scale_colour_manual(name="legend", values=c("blue", "red"))

enter image description here

erc
  • 10,113
  • 11
  • 57
  • 88
  • Thanks! Very beautiful solution! – R.Arkhipov Mar 29 '16 at 08:55
  • 3
    And of course you can use the labels property in the scale_colour_manual to change the label of A and B. – Sid Apr 18 '17 at 16:41
  • The fill colour in the legend gets darkened and takes the colour that is displayed when the two confidence intervals intersect. Is there a way to prevent such a behaviour from happening ? – Sileo Oct 14 '20 at 17:50
  • @Rphad I don't have an answer to your question. If it has not been asked already elsewhere on SO you may ask a new question to get more attention. – erc Oct 15 '20 at 09:34
  • 1
    @beetroot I actually did and got an answer! https://stackoverflow.com/questions/64359233/ – Sileo Oct 15 '20 at 15:11