---
layout: post
title: "How to add text to a figure using the R ggplot2 package with geom_text (CC149)"
blurb: "Replacing a legend with text labels"
author: "PD Schloss"
date: 2021-09-27 11:00
comments: false
youtube: uMS59hsi_JY
start_hash: cfbbd59dc4d9102c52b002c795ed6d5e480b207a
end_hash: 9f367142997c366f7b44703bdfab2a478123b985
---

Adding text labels to your figure to tell your audience what group each point or line comes from. Thankfully, it's relatively easy to pull this off in R using ggplot2's geom_text function. We'll replace our legend with text annotations and talk about how we can make the labels easier to see. Along the way, we'll also learn about the modulus operator (%%) and get to see if_else and case_when in action. The data depict the percentage of people in 15 countries who would be willing to receive the COVID-19 vaccine as of August and October of 2020.

Pat uses the `geom_text` function function from `ggplot2` and a variety of functions from the `dplyr`, `showtext`, and `ggtext` packages in RStudio.

<iframe style="margin: 0 auto;display:block;" width="560" height="315" src="https://www.youtube.com/embed/{{ page.youtube }}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>


## Code

You can browse the state of the repository at the
* [beginning of the episode](https://github.com/riffomonas/vaccination_attitudes/tree/{{ page.start_hash }})
* [end of the episode](https://github.com/riffomonas/vaccination_attitudes/tree/{{ page.end_hash }})


### Data

The `august_october_2020.csv` data is available in the [GitHub repository](https://raw.githubusercontent.com/riffomonas/vaccination_attitudes/3f39b9e09618144874ced760c9a6332498e3a19c/august_october_2020.csv).

```
X.1,Total Agree - August 2020,Total Agree - October 2020
Total,77,73
India,87,87
China,97,85
South Korea,84,83
Brazil,88,81
Australia,88,79
United Kingdom,85,79
Mexico,75,78
Canada,76,76
Germany,67,69
Japan,75,69
South Africa,64,68
Italy,67,65
Spain,72,64
United States,67,64
France,59,54
```
