In this article, we will see how to add straight (vertical, horizontal and diagonal) lines to plots in base R and in ggplot2. As an example, we will use the median of x values for the vertical line, the median of y values for the horizontal line and custom intercept and slope values for the diagonal line.
Load the ggplot2 package
library(ggplot2)
Load the dataset
data("iris")
Variables assignment
dataset = iris
x_column = "Sepal.Length"
y_column = "Petal.Length"
X value for the vertical line
For the vertical line, we need to choose one value on the x axis such as the median for example:
xmed = median(dataset[, x_column])
Y value for the horizontal line
For the horizontal line, we need to choose one value on the y axis such as the median for example:
ymed = median(dataset[, y_column])
Intercept and slope for the diagonal line
And for the diagonal line, we need to choose the slope of the line as well as the intercept. We can set them manually, fit a linear regression line through the points or compute them from two points that we want the line to cross. In this tutorial, we will set them manually:
intercept = 2.2
slope = -8.2
Colors
Moreover, we will use a specific color for the three types of lines (vertical, horizontal, diagonal). If you want to learn more about the palette() colors or want to use other colors, have a look at my post about color palettes in R.
vcol = palette()[2]
hcol = palette()[3]
acol = palette()[4]
Add straight lines in base R
The three types of lines are added to base R plots with the abline function:
- v parameter for the x value of the vertical line
- h parameter for the y value of the horizontal line
- a and b parameters for the intercept and slope of the diagonal line
- lty parameter for line type
- lwd parameter for line size
plot(dataset[, x_column], dataset[, y_column], pch = 18,
xlab = x_column, ylab = y_column)
abline(v = xmed, lty = "dashed", col = vcol, lwd = 3)
abline(h = ymed, lty = "dashed", col = hcol, lwd = 3)
abline(a = intercept, b = slope, col = acol, lwd = 3)
Add straight lines in ggplot2
A vertical line is added with the geom_vline function, a horizontal line with the geom_hline function and a diagonal line with the abline function. lty and lwd parameters define line type and line size, respectively.
ggplot(dataset, aes_string(x = x_column, y = y_column)) +
geom_point(shape = 18)+
geom_vline(xintercept = xmed, lty = "dashed", col = vcol, lwd = 1)+
geom_hline(yintercept = ymed, lty = "dashed", col = hcol, lwd = 1)+
geom_abline(intercept = intercept, slope = slope, col = acol, lwd = 1)
Conclusion
In conclusion, it is really easy to add straight lines to plots in base R and in ggplot2. Which one were you looking for?