Adding regression lines
Regression lines are used to describe trends, it's not usual to have regression lines stacked with scatterplots. They can be drawn using ggplot2
, ggvis
, and plotly
. For the first two, adding regression lines will only require calling a function or two, to do the same using plotly
might require more lines of code.
This recipe's intention is to add regression lines to the scatterplots made from iris
data frame. Ordinary least squares (OLS) regression lines will be grouped by species. Drawing un-grouped regressions requests for fewer code, so once you have mastered how to group them, it's not difficult to work the other way around.
How to do it...
- Load
ggplot2
and call for thegeom_smooth()
layer:
> library(ggplot2) > scatter <- ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point(alpha = .5, aes(colour = Species, shape = Species)) > scatter + geom_smooth(method = 'lm', se = F, show.legend = F, ...