ggplot2 – 抖动和位置一起闪避

我试图从GGplot2研讨会http://dl.dropbox.com/u/42707925/ggplot2/ggplot2slides.pdf重新创build一个数字。

在这种情况下,我试图生成示例5,抖动数据点受到闪避。 当我运行代码时,点以正确的线为中心,但没有抖动。

这是直接从演示文稿的代码。

set.seed(12345) hillest<-c(rep(1.1,100*4*3)+rnorm(100*4*3,sd=0.2), rep(1.9,100*4*3)+rnorm(100*4*3,sd=0.2)) rep<-rep(1:100,4*3*2) process<-rep(rep(c("Process 1","Process 2","Process 3","Process 4"),each=100),3*2) memorypar<-rep(rep(c("0.1","0.2","0.3"),each=4*100),2) tailindex<-rep(c("1.1","1.9"),each=3*4*100) ex5<-data.frame(hillest=hillest,rep=rep,process=process,memorypar=memorypar, tailindex=tailindex) stat_sum_df <- function(fun, geom="crossbar", ...) {stat_summary(fun.data=fun, geom=geom, ...) } dodge <- position_dodge(width=0.9) p<- ggplot(ex5,aes(x=tailindex ,y=hillest,color=memorypar)) p<- p + facet_wrap(~process,nrow=2) + geom_jitter(position=dodge) +geom_boxplot(position=dodge) p 

编辑 :有ggplot2版本1.0.0使用position_jitterdodge更好的解决scheme。 参见@Didzis Elferts的答案。 请注意, dodge.width控制抖动的宽度, jitter.width控制抖动的宽度。

我不确定代码如何在PDF中生成图表。

但是,这样做会让你接近你以后的样子吗?

我将tailindexmemorypar转换为数字; 加在一起; 结果是geom_jitter图层的x坐标。 有可能是一个更有效的方法来做到这一点。 此外,我想看看如何geom_boxplotgeom_jitter ,并没有抖动,将产生PDF中的graphics。

 library(ggplot2) dodge <- position_dodge(width = 0.9) ex5$memorypar2 <- as.numeric(ex5$tailindex) + 3 * (as.numeric(as.character(ex5$memorypar)) - 0.2) p <- ggplot(ex5,aes(x=tailindex , y=hillest)) + scale_x_discrete() + geom_jitter(aes(colour = memorypar, x = memorypar2), position = position_jitter(width = .05), alpha = 0.5) + geom_boxplot(aes(colour = memorypar), outlier.colour = NA, position = dodge) + facet_wrap(~ process, nrow = 2) p 

在这里输入图像描述

ggplot2版本1.0.0有一个名为position_jitterdodge()新位置,用于这种情况。 这个位置应该在geom_point()内部使用,并且应该在aes()内部使用fill=来显示哪个variables来躲避你的数据。 要控制闪避参数的宽度dodge.width=应该被使用。

 ggplot(ex5,aes(x=tailindex ,y=hillest,color=memorypar,fill=memorypar)) + facet_wrap(~process,nrow=2) + geom_point(position=position_jitterdodge(dodge.width=0.9)) + geom_boxplot(fill="white",outlier.colour = NA, position = position_dodge(width=0.9)) 

在这里输入图像描述