8.3 Text labels

8.2 Text labels - geom_text() - geom_text() adds label text to the x and y coorindates of a graph such as name instead of a circle in a scatter plot.

  • Change the font with the family aesthetic

  • The packages showtext and extrafont can help with handling fonts across differnet devises

  • Change the fontface aesthetic for plain, bold, or italic “faces”.

  • Alignment: hjust (“left”, “center”, “right”, “inward”, “outward”) and vjust (“bottom”, “middle”, “top”, “inward”, “outward”) aesthetics.

  • vjust = “inward”, hjust = “inward” ensures labels stay in the plot

  • geom_text(aes(label = text), vjust = “inward”, hjust = “inward”)

df <- data.frame(x = 1, y = 3:1, face = c("plain", "bold", "italic"))
ggplot(df, aes(x, y)) + 
  geom_text(aes(label = face, fontface = face, ), 
  vjust = "inward", hjust = "inward", size = 20, angle = 10) 

base + 
  geom_text(aes(label = body_mass_g), check_overlap = TRUE)

base + 
  geom_label(aes(label = body_mass_g))

ggplot(mpg, aes(displ, hwy)) + 
  geom_text(aes(label = model)) + 
  xlim(1, 8)

ggplot(mpg, aes(displ, hwy)) + 
  geom_text(aes(label = model)) + 
  xlim(1, 8)

ggplot(mpg, aes(displ, hwy)) + 
  geom_text(aes(label = model), check_overlap = TRUE) + 
  xlim(1, 8)

library(ggrepel)
ggplot(mpg, aes(displ, hwy)) + 
  geom_text_repel(aes(label = model)) + 
  xlim(1, 8)

label <- data.frame(
  waiting = c(55, 80), 
  eruptions = c(2, 4.3), 
  label = c("peak one", "peak two")
)

ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_tile(aes(fill = density)) + 
  geom_label(data = label, aes(label = label))

geom_label