bluepole
bluepole

Reputation: 345

Why cannot I add legend through ggplot2?

I'm trying to add legend inside the plotting area with the following R code:

library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + 
    stat_smooth(method = "lm", formula = y ~ x, size = 1, se = FALSE, color = "black") + 
    stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1, se = FALSE, color = "blue") +
    theme(legend.justification=c(1,1), legend.position=c(0.85,0.85), legend.title=element_blank()) +
    scale_color_manual(values=c("black","blue"), labels=c("linear","quadratic")) 

enter image description here

However, I'm baffled why the legend does not show up as intended. Could someone help?

Upvotes: 0

Views: 44

Answers (1)

Duck
Duck

Reputation: 39595

You can try this:

library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + 
  stat_smooth(method = "lm", formula = y ~ x , size = 1, se = FALSE, aes(color = "black")) +
  stat_smooth(method = "lm", formula = y ~ x + I(x^2), size = 1, se = FALSE, aes(color = "blue"))+
  scale_color_manual(values=c("black","blue"), labels=c("linear","quadratic"))+
  theme(legend.justification=c(1,1), legend.position=c(0.85,0.85), legend.title=element_blank())

enter image description here

Upvotes: 2

Related Questions