1 Goal


The goal of this tutorial is to learn how to draw a linear model on top of a scatter plot using stat smooth in ggplot. This can be very useful when we want to see quickly the linear trends in our data.


2 Data preparation


# First we load the libraries
library(ggplot2)
library(ggthemes)

# In this example we will use the open repository of plants classification Iris. 
data("iris")
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
# We draw the petal length vs the petal width
ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) + geom_point(aes(color = Species))


3 Adding linear model

3.1 Simple configuration


# With the function stat_smooth we can add a linear fit to our data points
# We should define the method used for smoothing the data, in this case lm
# To see other methods check ?stat_smooth
ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) + geom_point(aes(color = Species)) + stat_smooth(method = "lm")


3.2 Removing the confidence level


# We can see that a 0.95 confidence level is shown by default
# We can remove the confidence level by defining se as false
ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) + geom_point(aes(color = Species)) + stat_smooth(method = "lm", se = FALSE)


3.3 Changing the confidence level


# We can see that a 0.95 confidence level is shown by default
# We can change the confidence level
ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) + geom_point(aes(color = Species)) + stat_smooth(method = "lm", level = 0.99)


4 Creating one linear model per class


# We know that only definitions inside of ggplot are inherited in the following functions
# We can create a different linear model per class if we define the color inside of the ggplot call
ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length, color = Species)) + geom_point() + stat_smooth(method = "lm", level = 0.99)


5 Conclusion


In this tutorial we have learnt how to introduce a linear model to our data points in one simple instruction of ggplot. We can add one linear model for all the data or create one per different class.