Annotate with geom_text in R GGplot2
| |

Annotate with Geom_text in GGplot2

The function geom_text() can be used to annotate on graphs in GGplot2. Geom_text() uses data frames to annotate. Other functions such as annotate() can also be used to annotate in GGplot2. The annotate() function is described in this other post.

The dataset

The following dataset is used below to illustrate how to annotate on a graph using the geom_text() function.

Let us assume we would like to summarize the number of oranges you ate in the first half of the year. The following three lines of code create a dummy dataset for us.

#Generates each month and orders them accordingly
month <- fct_reorder(c("JAN","FEB","MAR","APR","MAY","JUN"), seq(1,6))

#Generates total number of oranges from a uniform distribution
total <- round(runif(6, min=2, max=30), digits = 0)

#Puts all generated data together
orange1 <- data.frame(month, total)
Here is what the orange1 dummy dataset looks like.

Annotate using Geom_text in R

#A. Creates a bargraph
a <- ggplot(data=orange1, aes(x=month, y=total)) +
        geom_bar(stat="identity", color="black", fill="#eeaa99", width=0.8) +
        ylim(0, 30) +
        labs(y = "Total No. of Oranges", x = "Month") +
        theme_classic()
a

#B. Annotates above each bar
b <- a + geom_text(aes(label = total))
b

#C. Annotates above each bar using geom_label instead of geom_text
c <- a + geom_label(aes(label = total))
c

#D. Adjusts the position and size of the labels
d <- a + geom_text(aes(label = total), size=10, vjust = 0, nudge_y = 0.5)
d

#E. Adjusts the position and size when using geom_label
e <- a + geom_label(aes(label = total), fill='black', color='white', size=5, vjust=1.1)
e
bargraph
A. The bar graph without annotation
Annotate on bargraph with geom_text
B. Annotate on a bar graph using geom_text
B. Annotate on a bar graph using geom_label
position and size in geom_text()
Adjust the position and size of the label when using geom_text()

Other Parameters in Geom_text()

The parameter hjust= can also be used to adjust the text horizontally. When there are overlaps with the annotations on the graph, the parameter check_overlap = TRUE can be used to remove overlaps. If annotates are done at the edges of the graph such that some of the texts are cut off, the following arguments can be used to resolve this: geom_text(vjust = “inward”, hjust = “inward”, …).

Finally, let us round off this article by illustrating how to rotate the text.

#Rotate the labels
a + geom_text(aes(label = month), angle=40, color='blue')
rotate in geom_text
Rotate labels using geom_text

Similar Posts

Leave a comment

One Comment