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
