How to Draw Lines to gglot2 Graphic in R (4 Examples)
In this tutorial you’ll learn how to draw vertical and horizontal lines to a ggplot2 graph in R programming.
Setting up the Examples
data(iris) # Loading example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
my_plot <- ggplot(iris, # ggplot2 graphic without lines aes(Sepal.Length, Sepal.Width)) + geom_point() my_plot |
my_plot <- ggplot(iris, # ggplot2 graphic without lines aes(Sepal.Length, Sepal.Width)) + geom_point() my_plot
Example 1: Drawing Vertical Line to ggplot2 Graphic
my_plot + # Adding vertical line to plot geom_vline(xintercept = 5) |
my_plot + # Adding vertical line to plot geom_vline(xintercept = 5)
Example 2: Drawing Horizontal Line to ggplot2 Graphic
my_plot + # Adding horizontal line to plot geom_hline(yintercept = 3) |
my_plot + # Adding horizontal line to plot geom_hline(yintercept = 3)
Example 3: Drawing Vertical & Horizontal Lines to ggplot2 Graphic
my_plot + # Adding vertical & horizontal lines geom_vline(xintercept = 5) + geom_hline(yintercept = 3) |
my_plot + # Adding vertical & horizontal lines geom_vline(xintercept = 5) + geom_hline(yintercept = 3)
Example 4: Drawing Multiple Vertical Lines to ggplot2 Graphic
my_plot + # Adding multiple lines to plot geom_vline(xintercept = seq(5, 7, by = 0.5)) |
my_plot + # Adding multiple lines to plot geom_vline(xintercept = seq(5, 7, by = 0.5))
Further Resources & Related Articles
Below, you can find some additional resources that are similar to the topic of this page: