Draw Different Lines to ggplot2 Facet Grid in R (Example Code)

In this tutorial you’ll learn how to annotate different lines to a ggplot2 facet grid in R programming.

Setting up the Example

data(iris)                                                # 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 ggplot2 package
library("ggplot2")                                        # Load ggplot2 package
my_plot <- ggplot(iris,                                   # Draw ggplot2 facet grid
              aes(x = Petal.Width,
                  y = Sepal.Length)) +
  geom_point() +
  facet_grid(~ Species)
my_plot

r graph figure 1 draw different lines ggplot2 facet grid r

Example: Annotate Different Lines to ggplot2 Facet Plot

iris_vline <- data.frame(Species = unique(iris$Species),  # Specify data with line parameters
                         lines = c(1, 2.2, NA),
                         colors = c(2, 3, NA),
                         sizes = c(5, 2, NA))
iris_vline                                                # Display data for lines
#      Species lines colors sizes
# 1     setosa   1.0      2     5
# 2 versicolor   2.2      3     2
# 3  virginica    NA     NA    NA
my_plot +                                                 # Add different lines to facet plot
  geom_vline(data = iris_vline,
             aes(xintercept = lines),
             color = iris_vline$colors,
             size = iris_vline$sizes)

r graph figure 2 draw different lines ggplot2 facet grid r

Further Resources

Please find some related R tutorials on topics such as text elements, graphics in R, plot legends, and colors in the following list.

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