Adding Annotations and Reference Lines
You'll learn how to enhance your ggplot2 visualizations by adding text labels, reference lines, and shapes to highlight key information and guide interpretation.
The Core Idea
Sometimes your data tells most of the story, but certain points need extra emphasis. Maybe you want to label an outlier, draw a line at the average value, or highlight a threshold. In ggplot2, you add these elements as annotation layers on top of your existing geoms.
Think of it like marking up a printed chart with a highlighter and pen—you're adding context that isn't part of the raw data but helps readers understand what matters.
The Three Key Functions
annotate() adds text, shapes, or segments directly to your plot. You specify exactly where (using x and y coordinates) and what to display:
ggplot(data, aes(x = year, y = sales)) +
geom_line() +
annotate("text", x = 2020, y = 50000, label = "Peak sales")
geom_hline() draws horizontal reference lines—perfect for showing means, medians, or thresholds:
ggplot(data, aes(x = category, y = value)) +
geom_point() +
geom_hline(yintercept = 100, linetype = "dashed", color = "red")
geom_vline() draws vertical reference lines, useful for marking time points or category boundaries:
ggplot(data, aes(x = date, y = price)) +
geom_line() +
geom_vline(xintercept = as.Date("2020-03-01"), color = "blue")
You can also use annotate() with "rect" or "segment" to add shapes or arrows that direct attention to specific regions of your plot.
Key Takeaway: Use annotate() for text and custom shapes, geom_hline() for horizontal reference lines, and geom_vline() for vertical reference lines to add contextual information that helps viewers interpret your visualizations more effectively.