1

I have the following boxplots which I made from:

#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

I'd like to colour the 3rd, 9th and 12th boxplot a specific colour: green, red and purple. Is this possible?

I tried the following without success:

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

E.g. like this:

enter image description here

HCAI
  • 2,213
  • 8
  • 33
  • 65
  • It's much harder to help with plotting question if you don't provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data. – MrFlick Mar 10 '17 at 16:53

1 Answers1

3

The easiest approach to do that is to:

  1. Add a column to your data frame with the colors you want to use
  2. Map the column to the fill aesthetic in ggplot.
  3. Use + scale_fill_identity() to map the values of your columns to the color they represent.
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

zeehio
  • 4,023
  • 2
  • 34
  • 48