抖動點圖:選圖與判讀指南
抖動點圖適合回答什麼問題?
抖動點圖顯示每個觀測;僅沿水平方向抖動可分開重疊點,同時保留 y 值。
本文目錄
我會控制抖動幅度,讓點仍明確屬於各自組別;密度著色是可選的補充。
實際執行的範例圖是什麼樣?
下方是本站對應範例實際產生的完整結果,附輸入資料與可執行程式。
本文使用模擬示範資料。

如何重現這個範例?
將程式存入可寫入目錄,安裝所需套件後執行 Rscript example.R。原例實測環境:R 4.5.3 · ggplot2 4.0.4。
以下是本文使用的程式碼、資料與結果檔案。你可以下載程式碼跟著操作,也可以開啟結果檔案,對照自己執行後的結果。
- example.R可在電腦上執行的完整範例程式碼。
- synthetic.csv本例使用的輸入資料,可用表格開啟。
- after.png依本文設定產生的結果圖。
- after.pdfPDF 格式的結果圖,方便檢視與排版。
- 使用授權 · LICENSE.txt說明程式碼、資料與圖表的使用條件,並附來源及字型授權。
完整原始程式
# 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))
接著應該查看哪篇具體解答?
具體解答說明這張結果圖對應的參數設定。
詳細操作解答目前提供英文、簡中與日文;下列連結開啟英文版。
Color individual observations by local density
技術依據: ggplot2 1
從零開始學習R語言

