Draw ggplot2 Line Chart with Labels at Ends of Lines (Example Code)

In this article you’ll learn how to draw a ggplot2 line graph with labels at the end of each line in the R programming language.

Setting up the Example

data(iris)                         # Example data
iris_mod <- iris
iris_mod$x <- rep(1:(nrow(iris_mod)/ length(table(iris_mod$Species))), 3)
iris_mod$label <- NA
iris_mod$label[which(iris_mod$x == max(iris_mod$x))] <- as.character(iris_mod$Species[which(iris_mod$x == max(iris_mod$x))])
head(iris_mod)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species x label
# 1          5.1         3.5          1.4         0.2  setosa 1  <NA>
# 2          4.9         3.0          1.4         0.2  setosa 2  <NA>
# 3          4.7         3.2          1.3         0.2  setosa 3  <NA>
# 4          4.6         3.1          1.5         0.2  setosa 4  <NA>
# 5          5.0         3.6          1.4         0.2  setosa 5  <NA>
# 6          5.4         3.9          1.7         0.4  setosa 6  <NA>

install.packages("ggplot2")        # Install & load ggplot2 package
library("ggplot2")

my_plot <- ggplot(iris_mod, # ggplot2 plot without labels aes(x = x, y = Sepal.Length, col = Species)) + geom_line() my_plot

install.packages("ggrepel")        # Install ggrepel package
library("ggrepel")                 # Load ggrepel

<pre lang="php">my_plot +                          # ggplot2 plot with labels
  geom_label_repel(aes(label = label),
                   nudge_x = 1,
                   na.rm = TRUE) +
  theme(legend.position = "none")

r graph figure 1 draw ggplot2 line chart labels at ends lines

Related Articles & Further Resources

Have a look at the following R tutorials. They discuss topics such as plot legends, labels, and colors.

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