This week, we will see how to connect two points with a straight line in base R and ggplot2. For this, we need to compute the slope and the intercept.
Example
x1 = 1
x2 = 8
y1 = 5
y2 = 9
Compute the slope
First, the slope is determined with the coordinates of the two points:
slope = (y1-y2) / (x1-x2)
Compute the intercept
Then, the intercept is calculated with the slope and the coordinates of one of the two points:
intercept = y1 - slope * x1
As a result, we obtain a diagonal line whose equation is y = 0.57x + 4.4.
Connect two points in base R
To add the straight diagonal line that crosses the two points in base R, we need to use the abline function. The line color comes from the palette function. Please read my post about color palettes in R if you want to know more about coloring.
plot(c(x1, x2), c(y1, y2), pch = 18, xlab = "x", ylab = "y",
xlim = c(0, 10), ylim = c(0, 10), cex = 3)
abline(a = intercept, b = slope, col = palette()[4], lwd = 3)
Connect two points in ggplot2
Finally, we need to use the geom_abline function to add the same diagonal line in ggplot2:
library(ggplot2)
ggplot(data.frame(x = c(x1, x2), y = c(y1, y2)), aes_string(x = "x", y = "y")) +
geom_point(shape = 18, size = 7)+
scale_x_continuous(limits = c(0, 10), n.breaks = 6)+
scale_y_continuous(limits = c(0, 10), n.breaks = 6)+
geom_abline(intercept = intercept, slope = slope, col = palette()[4], lwd = 1)
Conclusion
In conclusion, this post shows how to compute the slope and the intercept from the coordinates of two points and how to add the line that crosses these two points in base R and ggplot2.