Why does after_stat(density) fail in a ggplot2 jitter plot?

How can I color the original jittered points by density?

ggplot2: geom_jitter uses stat="identity", so calculate KDE (h=0.5) before colour=kde; after_stat(density) needs a density statistic.

On this page

Published and tested 22 November 2026.

after_stat() selects a variable already produced by a layer's statistic. The complete example below first triggers the error, then uses an explicit Gaussian kernel estimate at each original observation. It requires only ggplot2 and base R functions.

What do the before and after plots show?

The corrected plot colors each observation by its group's estimated density at that observation's original y value. Darker blue means higher estimated density. Both plots use the same observations and the same seeded horizontal jitter; vertical jitter is zero. The legend makes the corrected plotting area narrower, so pixel positions shift while data coordinates stay fixed.

I keep the jitter seed fixed while comparing the colours. That lets me find the same observation again even if the legend changes the size of the plotting area.

Before: 10 gray points in each of groups A and B, with original y values retained
Before: an ordinary jitter plot with a single point color.
After: the same 20 observations colored by within-group Gaussian KDE, with a density legend in inverse arbitrary units
After: color represents KDE in inverse arbitrary units. Read the color using the density scale in the legend.

How is the density calculated and checked?

For each observation y, average the Gaussian density centered at every value in the same group, including y itself. Each kernel uses bandwidth h=0.5 a.u. The estimate is sum(exp(-0.5*((y-yj)/h)^2)) / (n*h*sqrt(2*pi)). The density is calculated directly at each observation. The bandwidth is a demonstration choice and changes the resulting colors.

This article uses simulated example data. There are 20 values, 10 in each group. A uses 0,0.2,0.3,0.4,0.5,0.6,0.7,0.8,1.2,2.5; B uses 0,0.5,1,1.5,2,2.5,3,3.5,4,4.5.

Independent Python arithmetic matched all 20 density values within 1e-12. Group A ranges from 0.08297813 to 0.59516984; B from 0.13989423 to 0.19999970. The plotted y values and data-scale jittered x positions match before and after. The common color range is 0–0.6.

Which code produces the error and corrected exports?

Run Rscript --vanilla example.R with R 4.5.3 and ggplot2 4.0.4. The script catches the deliberate error, writes it to actual-error.txt, and generates both complete 1200×900 PNGs and a corrected 6×4.5 inch PDF. Raw values, per-point density and position checks are downloadable CSVs.

# Original Bopbun synthetic input, code and figures: CC0-1.0.
library(ggplot2)
out <- dirname(normalizePath(sub('^--file=', '', grep('^--file=',commandArgs(),value=TRUE)[1])))
d <- data.frame(group=rep(c('A','B'),each=10),
  value=c(0,.2,.3,.4,.5,.6,.7,.8,1.2,2.5,0,.5,1,1.5,2,2.5,3,3.5,4,4.5))
d$id <- seq_len(nrow(d))
write.csv(d,file.path(out,'synthetic.csv'),row.names=FALSE)
# Gaussian kernel estimate at each observation, calculated within its group.
h <- 0.5
d$kde <- NA_real_
for (g in unique(d$group)) {
  i <- which(d$group==g)
  y <- d$value[i]
  d$kde[i] <- vapply(y,function(v) mean(dnorm(v,mean=y,sd=h)),numeric(1))
}
write.csv(d,file.path(out,'point-density.csv'),row.names=FALSE)
base <- ggplot(d,aes(group,value)) +
  scale_y_continuous(breaks=0:5,limits=c(-.25,5)) +
  labs(x='Group',y='Value (a.u.)') + theme_classic(base_size=13)
pos <- position_jitter(width=.12,height=0,seed=23)
before <- base + geom_point(position=pos,size=3,colour='#666666')
after <- base + geom_point(aes(colour=kde),position=pos,size=3) +
  scale_colour_gradient(low='#dbe9f6',high='#163f70',limits=c(0,.6),
                        name='KDE\n(1/a.u.)')
bad <- base + geom_jitter(aes(colour=after_stat(density)),width=.12,height=0)
message <- tryCatch({ggplot_build(bad);'unexpected success'},error=function(e)conditionMessage(e))
writeLines(message,file.path(out,'actual-error.txt'))
stopifnot(grepl('density',message),message!='unexpected success')
b <- ggplot_build(before)$data[[1]]
a <- ggplot_build(after)$data[[1]]
stopifnot(nrow(a)==20,identical(a$x,b$x),identical(a$y,b$y),identical(a$y,d$value))
write.csv(data.frame(id=d$id,source_y=d$value,before_x=b$x,after_x=a$x,
  before_y=b$y,after_y=a$y),file.path(out,'position-check.csv'),row.names=FALSE)
ggsave(file.path(out,'before.png'),before,width=6,height=4.5,units='in',dpi=200,bg='white')
ggsave(file.path(out,'after.png'),after,width=6,height=4.5,units='in',dpi=200,bg='white')
ggsave(file.path(out,'after.pdf'),after,width=6,height=4.5,units='in',bg='white',timestamp=FALSE)
sink(file.path(out,'session-info.txt')); print(sessionInfo()); sink()
print(aggregate(kde~group,d,range))

What should I check before using this on my own data?

Choose the bandwidth in the y variable's units, inspect how it affects the colors, and keep the same bandwidth when comparing groups on a common density scale. Each group is normalized by its own n; the color scale describes density within each group. Validate missing values and group sizes before applying this minimal example. It implements an unbounded Gaussian KDE, without boundary correction or automatic bandwidth selection.

These are the code, data and result files used in this article. Choose a file below to run the example or compare your results.

geom_jitter 4.0.4 · after_stat · R dnorm

The PNG uses Windows Arial 7.03. The PDF uses standard Helvetica without embedding a font file; other viewers can substitute the font. Windows font output terms

SHA256

Research figure questions · Histogram density