liveBook · Manning

Geom_text() function

As explained in Statistics Slam Dunk

The ggplot2 geom_text() function draws text labels at positions specified by aesthetic mappings.

geom_text() adds text labels or annotations to a ggplot2 visualization. It places labels using aesthetic mappings, so each label can display a value associated with a plotted observation. section 2.5.5 section 2.5.4

Common uses include:

  • Labeling bar heights with summarized values such as means, medians, or seasonal scoring averages. section 2.5.5 section 14.3
  • Annotating a correlation matrix with rounded correlation coefficients displayed inside heat-map tiles. section 2.5.4
  • Adding counts to faceted horizontal bars, where vjust and hjust control vertical and horizontal label placement. section 9.5.2

Labeling average NBA win shares

After summarizing career win shares by place of birth, map Born2 to x and meanWS to y, draw bars, and add geom_text(aes(label = trunc(meanWS), vjust = -0.3)). The labels show whole-number averages above each bar; ylim(0, 35) leaves room for them. section 2.5.5

p5 <- ggplot(tenth_tibble, aes(x = Born2, y = meanWS)) + 
 geom_bar(stat = "identity", width = .5, fill  = "darkorchid4") + 
 labs(title = "Average Win Shares by Place of Birth",
      subtitle = "2000-09 NBA Drafts", 
      x = "Where Born", 
      y = "Average Career Win Shares") + 
 geom_text(aes(label = trunc(meanWS), vjust = -0.3)) +
 ylim(0, 35) +
 theme(plot.title = element_text(face = "bold"))

p6 <- ggplot(tenth_tibble, aes(x = Born2, y = medianWS)) + 
 geom_bar(stat = "identity", width = .5, fill  = "sienna1") + 
 labs(title = "Median Win Shares by Place of Birth",
      subtitle = "2000-09 NBA Drafts", 
      x = "Where Born", 
      y = "Median Career Win Shares") + 
 geom_text(aes(label = trunc(medianWS), vjust = -0.3)) +
 ylim(0, 35) +
 theme(plot.title = element_text(face = "bold"))

Compare the complete ggplot2 code for placing mean and median win-share labels on two bar charts. section 2.5.5

How Statistics Slam Dunk covers it

How deep it goes
Demonstrates mapped labels, rounding, and vjust or hjust placement, but does not descend into geom internals.
Examples
Uses NBA win-share bars, correlation-coefficient tiles, seasonal scoring bars, and faceted home-away win counts.
What it assumes
Assumes basic ggplot2 chart construction and aesthetic mappings while demonstrating label rounding and position adjustments.
What you can do after
Apply it via ggplot2 to place readable values and annotations on bars, tiles, and faceted charts.
How it connects
Connects ggplot2 layering with aesthetic mappings, bar charts, heat maps, correlation matrices, faceting, vjust, hjust, and ylim.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.