在ggplot2中仅填充颜色的特定箱图

时间:2017-03-10 16:51:28

标签: r ggplot2

我有以下框图:我是从

创建的
#Data
set.seed(395)
Env<- data.frame(CO2= c(cumsum(rnorm(1*36)), cumsum(rnorm(1*36))),
                  Group= rep(c("A","B"), each=36),
                  Segment=rep(seq(1,12),each=36))

ggplot(data=subset(Env, !is.na(Segment)),aes(factor(Segment),CO2))+
  geom_boxplot()+
  facet_wrap(~ Group)+
  theme_bw()+
  labs(x="Time segment", y="CO2")

enter image description here

我想为第3,第9和第12个方框图上的特定颜色着色:绿色,红色和紫色。这可能吗?

我尝试了以下但没有成功:

scale_fill_manual(values = c("", "","green","","","","","","red","","","purple"))

E.g。像这样:

enter image description here

1 个答案:

答案 0 :(得分:3)

最简单的方法是:

  1. 使用您要使用的颜色为数据框添加一列
  2. 将列映射到ggplot中的fill美学。
  3. 使用+ scale_fill_identity()将列的值映射到它们所代表的颜色。
  4. set.seed(395)
    Env<- data.frame(CO2= c(cumsum(rnorm(1*36)), cumsum(rnorm(1*36))),
                      Group= rep(c("A","B"), each=36),
                      Segment=rep(seq(1,12),each=36))
    
    Env$fillcol <- NA
    Env$fillcol[Env$Segment %in% c(3,9,12) & Env$Group == "A"] <- "red"
    Env$fillcol[Env$Segment %in% c(2,10,12) & Env$Group == "B"] <- "blue"
    
    ggplot(data=subset(Env, !is.na(Segment)),aes(x = factor(Segment), y = CO2, fill = fillcol)) +
      geom_boxplot()+
      facet_wrap(~ Group)+
      theme_bw()+
      labs(x="Time segment", y="CO2") +
      scale_fill_identity()
    

    Result