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
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

r graph figure 1 draw lines gglot2 graphic

Example 1: Drawing Vertical Line to ggplot2 Graphic

my_plot +                      # Adding vertical line to plot
  geom_vline(xintercept = 5)

r graph figure 2 draw lines gglot2 graphic

Example 2: Drawing Horizontal Line to ggplot2 Graphic

my_plot +                      # Adding horizontal line to plot
  geom_hline(yintercept = 3)

r graph figure 3 draw lines gglot2 graphic

Example 3: Drawing Vertical & Horizontal Lines to ggplot2 Graphic

my_plot +                      # Adding vertical & horizontal lines
  geom_vline(xintercept = 5) +
  geom_hline(yintercept = 3)

r graph figure 4 draw lines gglot2 graphic

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))

r graph figure 5 draw lines gglot2 graphic

Further Resources & Related Articles

Below, you can find some additional resources that are similar to the topic of this page:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top