简体   繁体   中英

Faceted grouped boxplot r with or without ggplot2

I have a set of experiments done over 10 phases or months. I'm growing bacteria of 3 different TYPES and counting the growth (ACC).

I'm trying to get a facet_wrap grouped boxplot of growth over different phases for the three bacteria types (A,E and H). My data:

head(EAH)
  ACC sample site bed phase X.M.SA TYPE
1  SG      A    1   0     1     NO    E
2  SG      A    2   0     1     NO    A
3  MG      A    3   0     1     NO    H
4  SG      A    4   0     1     NO    A
5  LG      A    1   0     2     NO    E
6  LG      A    2   0     2     NO    H

Some representative data that doesn't work for some reason:

EAH<- data.frame(ACC=factor(sample(1:5,10,replace=T), label=c("NG","SG","LG","MG","GH")), 
                 Phase=factor(seq(1,10,1)),
                 TYPE=factor(sample(1:3,10,replace=T), label=c("A","E","S"),replace=T))

I'm trying ggplot2 although if it can be done without that's ok too.

ggplot(EAH, aes(x=as.factor(EAH$phase), y=EAH$ACC, group=EAH$TYPE)) + 
  geom_boxplot(aes(fill=factor(EAH$TYPE)))+ facet_grid(. ~ as.factor(EAH$phase))

Here's what I've managed so far but can't get it to facet:

在此处输入图片说明

Something like the 3rd graph down on this post looks good: ggplot: arranging boxplots of multiple y-variables for each group of a continuous x

EDIT

New code is close but I've had to change ACC to numeric. Can I get the labels back as NG, SG, LG, MG, HG on the y axis?

ggplot(EAH, aes(x=TYPE, y=as.numeric(ACC))) + 
  geom_boxplot(aes(fill=TYPE))+ facet_grid(. ~ phase)

在此处输入图片说明

Final code:

library(RColorBrewer)
library(ggplot2)
ggplot(EAH, aes(x=TYPE, y=as.numeric(ACC))) + 
  geom_boxplot(aes(fill=TYPE))+ 
  facet_grid(. ~ phase) +
 labs(x = "Phase", y = "Growth",color="Type" )+
 scale_fill_brewer(palette="Blues")+
 theme_bw()+
 theme(strip.background=element_rect(fill="black"))+
 theme(strip.text=element_text(color="white", face="bold"))+
scale_y_discrete(breaks=c("1", "2", "3","4","5"),
                   labels=c("NG", "SG", "LG","MG","HG"))

And Result: 在此处输入图片说明

ggplot2 uses non-standard evaluation. It looks for variables in the data.frame passed to its data parameter. So you can simply do this:

ggplot(EAH, aes(x=Phase, y=ACC)) + 
  geom_boxplot(aes(fill=TYPE))+ facet_grid(. ~ Phase)

And of course, R is case sensitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM