This is question that's been asked many times, I know, but I still can't figure out a good answer. I would like to get a pretty legend that shows manually-added lines in a separate legend on the plot. Here's what I've figured out so far:
library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10))) +
geom_abline(aes(intercept=25, slope = (-1/30)))
gives:
which has manually-added lines, but no legend entry for them.
Attempt 1
Just adding show.legend=TRUE
isn't very helpful:
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10)), show.legend = TRUE) +
geom_abline(aes(intercept=25, slope = (-1/30)), show.legend = TRUE)
Attempt 2
Adding an artificial fill
for each additional line isn't very helpful, either:
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10), fill='Comparison Line 1')) +
geom_abline(aes(intercept=25, slope = (-1/30), fill='Comparison Line 2'))
it just gives a warning and returns the original plot:
Warning: Ignoring unknown aesthetics: fill
Warning: Ignoring unknown aesthetics: fill
Attempt 3
Adding both show.legend=TRUE
and a fake aes fill
gets close, but the result is very ugly:
ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) +
theme_bw() +
geom_point() +
geom_smooth(method = 'lm', se=FALSE) +
geom_abline(aes(intercept=40, slope = (-1/10), fill='Comparison Line 1'), show.legend = TRUE) +
geom_abline(aes(intercept=25, slope = (-1/30), fill='Comparison Line 2'), show.legend = TRUE)
Finally, my question:
How do I get rid of the diagonal lines in the color legend (titled "factor(am)"), and how do I get normal-looking lines next to the items in the fill legend (titled "fill")?