2017-08-13 52 views
0

如何修改下面的代碼,其中「註釋函數」僅適用於oj部分。我的意思只是(setosa.VC和versicolor.VC)GGplot_annotate和facet_wrap函數

data("ToothGrowth") 
data('iris') 

iris2<-iris[c(1:10,50:60,100:110,61:70,11:20,111:118),] 

big_data<-cbind(iris2,ToothGrowth) #dummy data 
big_data$com <- with(big_data, interaction(Species,supp), drop = TRUE) 
big_data$N <- 4 
big_data$label <- paste0(big_data$com,"\n","(n=",big_data$N,")") 
plot<- ggplot(big_data, aes(label, len))+geom_boxplot()+facet_wrap(~supp, scales = "free_x") 

plot<- plot + annotate("rect", xmin = 1, xmax = 2, ymin = 35, ymax =35, alpha=1,colour = "black")+ 
    annotate("rect", xmin = 1, xmax = 1, ymin = 33, ymax =35, alpha=1, colour = "black")+ 
    annotate("rect", xmin = 2, xmax = 2, ymin = 33, ymax =35, alpha=1,colour = "black")  

回答

0

你可以欺騙facet_wrap繪製在OJ部分的矩形與數據的subset

ggplot(big_data, aes(label, len)) + 
    geom_boxplot() + 
    facet_wrap(~supp, scales = "free_x") + 
    geom_rect(data= subset(big_data, supp=="OJ"), 
      aes(xmin=1, xmax=2, ymin=35, ymax=35), alpha=1, colour="black") + 
    geom_rect(data= subset(big_data, supp=="OJ"), 
      aes(xmin=1, xmax=1, ymin=33, ymax=35), alpha=1, colour="black") + 
    geom_rect(data= subset(big_data, supp=="OJ"), 
      aes(xmin=2, xmax=2, ymin=33, ymax=35), alpha=1, colour="black") 

enter image description here