We will annotate our plots today.
Welcome to Day 18 of the “Viz with Me” series!
Today, we’ll learn how to add text annotations to a plot using the ggtext package. This will allow you to place custom text on your plot to highlight key points.
We’ll achieve this using a simple example with the Palmer Penguins dataset.
# Load the required libraries
library(tidyverse)
library(palmerpenguins)
library(ggtext)
# A scatter plot of bill length vs. body mass
ggplot(data = penguins, aes(x = bill_length_mm, y = body_mass_g)) +
geom_point() +
geom_text(aes(label = "Annotated text"), # Adding text annotation
x = 40, y = 6000, # Position of the text on the plot
size = 5, color = "blue") + # Text size and color
theme_classic()
label: This is the text you want to display on the plot.
x and y: The position coordinates where the text will appear. Here, I’ve manually set x = 40 and y = 6000 to place the text near the top of the plot.
size: Adjusts the size of the text.
color: Sets the color of the text.
If you want to put a beautiful box around the text, you can use geom_label()
instead of geom_text()
. It works the same way but adds a rectangle behind the text for emphasis.
Here’s an example:
ggplot(data = penguins, aes(x = bill_length_mm, y = body_mass_g)) +
geom_point() + # Scatter plot of data points
geom_label(aes(label = "Annotated with a box"), # Label with a box
x = 40, y = 6000, # Position
size = 5, fill = "lightyellow", # Text size and background color
color = "blue") +
theme_classic()
Using geom_label()
is especially helpful when you want your text to stand out clearly.
In addition to size and color, notice that the fill
argument is used to set the background color of the box around the text.
That’s it for today! You’ve learned how to add text annotations to your plots using geom_text()
and geom_label()
. These functions are handy for highlighting key points in your visualizations. Try them out in your next plot!
I hope you enjoyed today’s post. See you tomorrow for another exciting topic!
For attribution, please cite this work as
Soundararajan (2024, Oct. 18). My R Space: Day 18 of viz with me. Retrieved from https://github.com/soundarya24/SoundBlog/posts/2024-10-18-day-18-of-viz-with-me/
BibTeX citation
@misc{soundararajan2024day, author = {Soundararajan, Soundarya}, title = {My R Space: Day 18 of viz with me}, url = {https://github.com/soundarya24/SoundBlog/posts/2024-10-18-day-18-of-viz-with-me/}, year = {2024} }