R 小提琴图与盒图的结合

R 小提琴图与盒图的结合,r,plot,ggplot2,R,Plot,Ggplot2,我有一个非常简单的数据集(2组,每组n=15)。使用ggplot2,我可以轻松地绘制两组的小提琴图或方框图。然而,我想画一个小提琴图,但是让填充阴影对应于我数据的3个四分位数 有一个例子是在SAS中完成的,但我想在R中这样做。像这样使用ggplot\u build() 编辑更新以显示原始数据的分位数 require(ggplot2) # for ggplot require(dplyr) # for mutation df<-data.frame( # make sa

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


有一个例子是在SAS中完成的,但我想在R中这样做。

像这样使用
ggplot\u 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()
require(ggplot2)#对于ggplot
突变需要(dplyr)#

是的,谢谢!这就是我要找的。我不太确定代码到底是如何工作的,但是有没有可能通过分位数(df$grp)来分解多边形,而不是仅仅将垂直空间分解为25%的块?是的-我实际上是想这样做的,但是计算了小提琴坐标的分位数,这些分位数是有规律的间隔,而不是原始值-哎呀。我已经更正了代码,并翻转了图表,使它看起来更像您的示例。您知道如何让它与facet一起工作吗?如果我只添加一个facet_网格或facet_包裹,它看起来非常复杂。