You can see I set a different color per fitted line. Since I’m setting these colors as constants this is done outside aes().
ggplot(mtcars, aes(mpg, hp) ) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "black") +
geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE, color = "red") +
geom_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE, color = "blue")
I think for many people it feels intuitive to add the appropriate scale_*() function to the plotting code in hopes of getting a legend. Along those lines I’ll add scale_color_manual() to my plot.
ggplot(mtcars, aes(mpg, hp) ) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "black") +
geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE, color = "red") +
geom_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE, color = "blue") +
scale_color_manual(values = c("black", "red", "blue") )
I’ll move color inside of aes() within each geom_smooth() layer to construct color mappings. This adds a legend to the plot.
ggplot(mtcars, aes(mpg, hp) ) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, aes(color = "black") ) +
geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE, aes(color = "red") ) +
geom_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE, aes(color = "blue") )
One way to force ggplot to recognize the color names when they are inside aes() is to use scale_color_identity(). To get a legend with an identity scale you must use guide = “legend”. (The default is guide = “none” for identity scales.)
ggplot(mtcars, aes(mpg, hp) ) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, aes(color = "black") ) +
geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE, aes(color = "red") ) +
geom_smooth(method = "lm", formula = y ~ poly(x, 3), se = FALSE, aes(color = "blue") ) +
scale_color_identity(guide = "legend")
You can see I set a different color per fitted line. Since I’m setting these colors as constants this is done outside aes().
I think for many people it feels intuitive to add the appropriate scale_*() function to the plotting code in hopes of getting a legend. Along those lines I’ll add scale_color_manual() to my plot.
I’ll move color inside of aes() within each geom_smooth() layer to construct color mappings. This adds a legend to the plot.
One way to force ggplot to recognize the color names when they are inside aes() is to use scale_color_identity(). To get a legend with an identity scale you must use guide = “legend”. (The default is guide = “none” for identity scales.)