Plotting ggplot2 Scatterplot with Labels in R (Example Code)

On this page, I’ll explain how to add labels to a plot in R programming.

Preparing the Example

data(iris)                                       # Loading iris data
set.seed(942674)                                 # Set random seed
iris_small <- iris[sample(1:nrow(iris), 5), ]    # Modifying iris data
iris_small                                       # Show smaller iris data
#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 37           5.5         3.5          1.3         0.2     setosa
# 147          6.3         2.5          5.0         1.9  virginica
# 68           5.8         2.7          4.1         1.0 versicolor
# 84           6.0         2.7          5.1         1.6 versicolor
# 63           6.0         2.2          4.0         1.0 versicolor

Example: Drawing ggplot2 Scatterplot with Labels

install.packages("ggplot2")                      # Install ggplot2 package
library("ggplot2")                               # Load ggplot2 package
ggplot(iris_small,                               # Scatterplot with labels
       aes(Sepal.Length,
           Sepal.Width,
           label = Species)) +
  geom_point() +
  xlim(5.4, 6.4) +
  geom_text(aes(label = Species), vjust = 1)

r graph figure 1 plotting ggplot2 scatterplot labels r

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