结合小提琴情节与盒子情节

时间:2014-03-09 05:52:58

标签: r plot ggplot2

我有一个非常简单的数据集(2组,每组n = 15)。使用ggplot2,我可以轻松地绘制两组的小提琴情节或箱形图。但是,我想绘制一个小提琴图,但是填充阴影对应于我的数据的3个四分位数。

在SAS here中有一个例子,但我想在R。

中这样做

1 个答案:

答案 0 :(得分:11)

像这样使用ggplot_build()获取大纲?

编辑更新以显示原始数据的数量

require(ggplot2)   # for ggplot
require(dplyr)     # for mutation 

df<-data.frame(    # make sample data 
  grp=rep(1:6,each=15),
  val=c(rnorm(15,runif(1)*5,runif(1)),
        rnorm(15,runif(1)*5,runif(1)),
        rnorm(15,runif(1)*5,runif(1)),
        rnorm(15,runif(1)*5,runif(1)),
        rnorm(15,runif(1)*5,runif(1)),
        rnorm(15,runif(1)*5,runif(1))
        )
  )

g<-ggplot(df)+geom_violin(aes(x=grp,y=val,group=grp),color="darkred",fill="darkred",size=2)   # build the base violins

coords<-ggplot_build(g)$data        # use ggbuild to get the outline co-ords
d<-coords[[1]]                      # this gets the df in a usable form
groups<-unique(d$group)             # get the unique "violin" ids

# function to create geom_ploygon calls
fill_viol<-function(v,gr){
  quants<-mutate(v,x.l=x-violinwidth/2,x.r=x+violinwidth/2,cuts=cut(y,quantile(df[df$grp==gr,"val"]))) # add 1/2 width each way to each x value
  plotquants<-data.frame(x=c(quants$x.l,rev(quants$x.r)),   # left x bottom to top, then right x top to bottom
                         y=c(quants$y,rev(quants$y)),       # double up the y values to match
                         id=c(quants$cuts,rev(quants$cuts)))# cut by quantile to create polygon id
  geom_polygon(aes(x,y,fill=as.factor(id)),data=plotquants) # return the geom_ploygon object
}

g +                                                       # plot g
  lapply(groups,function(x)fill_viol(d[d$group==x,],x)) +   # plus polygon objects for each violin
  scale_fill_brewer(palette="Reds",                       # plus fill
                    name="Quantile\n",
                    labels=c("25","50","75","100")) +
  coord_flip()

enter image description here