繁体   English   中英

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

[英]Combining violin plot with box plot

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

有一个在SAS做一个例子在这里 ,但我想这样做的R.

像这样使用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()

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM