How to Annotate on a Graph with R GGplot2
Functions such as annotate() and geom_text() can be used to annotate a graph in GGPLOT2. This article focuses on the annotate() function which uses data passed in as vectors. The geom_text() function, which uses data frames, is covered in another article.
The following example is based on the iris dataset which is available in R. We will start with a simple scatterplot. Then we will calculate some summary statistics. And finally we will annotation the summary statistics on the plot.
#A. First a scatterplot with no annotation
a <- ggplot(iris, aes(x=Species, y=Sepal.Length)) +
geom_point(position = position_jitter(), size = 2, aes(shape = Species, colour=Species)) +
ylim(4, 8) +
theme_classic()
a
#count number of records per species and calculate the mean value per species
sstats <- iris %>%
group_by(Species) %>%
summarise(
count = n(),
meanSL = mean(Sepal.Length,na.rm=TRUE)
)
#B. annotate the number of records per Species
b <- a + annotate("text", x = sstats$Species, y = 4, label = paste0("N=", sstats$count))
b
#C. also annotate the mean value per Species
c <- b + annotate("text", x = sstats$Species, y = sstats$meanSL, label = paste0("N=", sstats$meanSL))
c
In plot C above, the x= and y= arguments of the annotate() function are specified such that the mean values are annotated at the location of the mean value on the y-axis.
The following code was used to annotate the featured image of this article:
ggplot(iris, aes(x=Species, y=Sepal.Length)) +
geom_point(position = position_jitter(), size = 2, colour = "grey", aes(shape = Species)) +
ylim(4, 8) +
theme_classic() +
annotate("text", x = 1.1, y = 7.5, label = "Annotate with", colour="red") +
annotate("text", x = 1.1, y = 7, label = "GGPLOT2 in R", colour="blue")