2017-03-09 4 views
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) 

enter image description here

답변

0

대신 변수의 고정 값 xgeom_violin 층을 추가 할 수있다.

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) 

enter image description here