Skip to content

Instantly share code, notes, and snippets.

@mmparker
Created July 18, 2013 21:48
Show Gist options
  • Save mmparker/6033426 to your computer and use it in GitHub Desktop.
Save mmparker/6033426 to your computer and use it in GitHub Desktop.
Example of annotating each ggplot2 facet with the number of points it displays
# Strings ain't factors
options(stringsAsFactors = FALSE)
library(ggplot2)
library(plyr)
# How many in each group?
cyl_count <- count(mtcars, "cyl")
# Make it a little prettier...
cyl_count$freq <- paste("N =", cyl_count$freq)
# Plot two layers with their own datasets
# Arbitrary x and y for the text positioning, although you get get algorithmic with it
# Na-na na na na na-na
ggplot() +
geom_point(data = mtcars, aes(x = disp, y = hp)) +
geom_text(data = cyl_count, aes(x = 400, y = 300, label = freq)) +
facet_wrap( ~ cyl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment