GGplot_annotate和facet_wrap函数

时间:2017-08-13 22:01:27

标签: r ggplot2

如何修改以下代码,“注释函数”仅适用于oj部分。我的意思是(setosa.VC和versicolor.VC)

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")    

1 个答案:

答案 0 :(得分: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