This post explains how to add text annotations to ggplots with lines and scatterplots using ggplot2 in R.
Disclaimer: This post is written by an AI language model based on R code provided by the author. The purpose is to document and explain R techniques for personal reference.
Adding text annotations to plots can greatly enhance their interpretability by providing context and highlighting key data points. In this post, we’ll learn how to add text to scatterplots with lines using the ggplot2
package in R.
Load the Required Library and Data:
Use the library(ggplot2)
function to load the ggplot2
package. We assume valg_NY
and alle_partier_23
are already loaded in your environment.
Create a Basic Scatterplot:
Use geom_point()
to create a scatterplot of H_21
vs. H_K23
.
Add Lines to the Plot:
geom_abline()
to add a line with a specified intercept and slope.geom_abline()
to add a stability line with intercept 0 and slope 1.Customize the Plot:
labs()
to add axis labels.theme_minimal()
for a clean theme.xlim()
and ylim()
to set axis limits.# Example data
valg_NY <- data.frame(
H_21 = runif(100, 0, 52),
H_K23 = runif(100, 0, 52),
Kommune = paste("Kommune", 1:100)
)
# Example regression coefficients for demonstration purposes
alle_partier_23 <- list(H = list(reg = list(coefficients = c(10, 0.5))))
# Indices for maximum and minimum values for annotation (dummy indices)
res_max_h <- which.max(valg_NY$H_21)
res_min_h <- which.min(valg_NY$H_21)
library(ggplot2)
# Create scatterplot with text annotations
plottet<-ggplot(valg_NY, aes(x = H_21, y = H_K23)) +
geom_point() + # Scatterplot
geom_abline(intercept = alle_partier_23$H$reg$coefficients[1],
slope = alle_partier_23$H$reg$coefficients[2],
color = "#0065F1",
linewidth = 0.8) + # Rikstendenslinjen
geom_abline(intercept = 0,
slope = 1,
linewidth = 0.8) + # Stabilitetslinjen
# Annotate min H
labs(x = "Prosent, stortingsvalget 2021",
y = "Prosent, kommunestyrevalget 2023") + # Axis labels
theme_minimal() + # Minimal theme
xlim(0, 52) + # X-axis limits
ylim(0, 52);plottet # Y-axis limits and print the plot
geom_text()
and annotate()
to label specific points on the plot.geom_text()
use data=
, annotate()
only needs you to specify x=
and y=
label=
and we can select a color=
, here the color of the Norwegian conservative party Høyre.plottet+
geom_text(label = "Rikstendenslinjen",
color = "#0065F1",
data = data.frame(H_21 = 36, H_K23 = 20)) + # Label for Rikstendenslinjen
geom_text(label = "Stabilitetslinjen",
data = data.frame(H_21 = 36, H_K23 = 40),
angle = 45) + # Label for Stabilitetslinjen
annotate("text",
x = valg_NY[res_max_h, "H_21"],
y = valg_NY[res_max_h, "H_K23"] + 2,
label = gsub(" -.*$", "", valg_NY[res_max_h, "Kommune"])) + # Annotate max H
annotate("text",
x = valg_NY[res_min_h, "H_21"] + 4,
y = valg_NY[res_min_h, "H_K23"],
label = gsub(" -.*$", "", valg_NY[res_min_h, "Kommune"])) +
xlim(0, 52) + # X-axis limits
ylim(0, 52)
geom_text_repel()
from the ggrepel
package for better text positioning to avoid overlaps. Here’s an example of how to use it: library(ggrepel)
ggplot(valg_NY, aes(x = H_21, y = H_K23)) +
geom_point() + # Scatterplot
geom_abline(intercept = alle_partier_23$H$reg$coefficients[1],
slope = alle_partier_23$H$reg$coefficients[2],
color = "#0065F1",
linewidth = 0.8) + # Rikstendenslinjen
geom_abline(intercept = 0,
slope = 1,
linewidth = 0.8) + # Stabilitetslinjen
geom_text_repel(label = "Rikstendenslinjen",
color = "#0065F1",
data = data.frame(H_21 = 36, H_K23 = 20)) + # Label for Rikstendenslinjen
geom_text_repel(label = "Stabilitetslinjen",
data = data.frame(H_21 = 46, H_K23 = 40),
angle = 4) + # Label for Stabilitetslinjen
annotate("text",
x = valg_NY[res_max_h, "H_21"],
y = valg_NY[res_max_h, "H_K23"] + 2,
label = gsub(" -.*$", "", valg_NY[res_max_h, "Kommune"])) + # Annotate max H
annotate("text",
x = valg_NY[res_min_h, "H_21"] + 4,
y = valg_NY[res_min_h, "H_K23"],
label = gsub(" -.*$", "", valg_NY[res_min_h, "Kommune"])) + # Annotate min H
labs(x = "Prosent, stortingsvalget 2021",
y = "Prosent, kommunestyrevalget 2023") + # Axis labels
theme_minimal() + # Minimal theme
xlim(0, 52) + # X-axis limits
ylim(0, 52) # Y-axis limits
Adjust the position of the text labels with the hjust
and vjust
arguments in geom_text()
for finer control.
You can also use annotate("text", ...)
for more complex or customized text annotations that require specific positioning or formatting outside the scope of the data aesthetics.
Adding text annotations to ggplots in R can significantly enhance the readability and informativeness of your visualizations. By using geom_text
, annotate
, and geom_text_repel
, you can effectively label key points and lines, providing important context and insights for your audience. Customize the text position, color, and angle to suit your needs and make your plots more engaging and informative.
For attribution, please cite this work as
Solheim & Writer) (2024, Dec. 20). Solheim: Adding Text to ggplots with Lines and Scatterplots. Retrieved from https://www.oyvindsolheim.com/library/Adding_text_ggplot2/
BibTeX citation
@misc{solheim2024adding, author = {Solheim, Øyvind Bugge and Writer), ChatGPT (Ghost}, title = {Solheim: Adding Text to ggplots with Lines and Scatterplots}, url = {https://www.oyvindsolheim.com/library/Adding_text_ggplot2/}, year = {2024} }