抖动点图:选择与读图指南
抖动点图适合回答什么问题?
抖动点图显示每个观测;仅沿水平方向抖动可分开重叠点,同时保留 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))
下一步应该查看哪篇具体解答?
具体解答解释这张结果图对应的参数设置。
技术依据: ggplot2 1
从零开始学习R语言

