0

ggplot 是否允许在不使用分组变量的情况下添加子图来显示整个样本,如图所示。

# example df
b<-abs(round(rnorm(500, sd=30)))
y<-runif(5)
pr<-y/sum(y)
names<-unlist(lapply(mapply(rep, LETTERS[1:5], 1:5), function (x) paste0(x, collapse = "") ) )
x <- sample(names, 500, replace=TRUE, prob=pr)
df<-data.frame(name=x,numbers=b)

#####replace this with something in the ggplot
dfdupli<-df
dfdupli$name<-"Whole sample"
dfrepeated<-rbind(df,dfwhole)
######

library(ggplot2)
violinplot_fun<-function(dataset,var,groupcol,adjust1,maxx) {
  ggplot(dataset)+
    geom_violin(aes_string(y = var, x=(groupcol)), scale="width", 
                alpha = 0.4, adjust=adjust1) + 
    scale_y_continuous(limits = c(0,ceiling(maxx)) , breaks=pretty_breaks(15) ) + 
    coord_flip()
} 

violinplot_fun(dfrepeated,"numbers", "name",0.5,100)

在此处输入图像描述

4

1 回答 1

0

您可以添加geom_violin具有固定x值而不是变量的第二层。

violinplot_fun <- function(dataset, var, groupcol, adjust1, maxx) {
    ggplot(dataset) +
        geom_violin(aes_string(y = var, x = groupcol), scale = "width", 
                  alpha = 0.4, adjust = adjust1) + 
        geom_violin(aes_(y = as.name(var), x = "Whole sample"), scale = "width", 
                  alpha = .4, adjust = adjust1) +
        scale_y_continuous(limits = c(0, ceiling(maxx)) , breaks = scales::pretty_breaks(15) ) + 
        coord_flip()
} 

violinplot_fun(df, "numbers", "name", 0.5, 100)

在此处输入图像描述

于 2017-03-09T19:24:38.303 回答