2017-10-18 111 views
1

我使用这个代码,以使箱线图:如何用ggplot2在x轴上绘制两列?

Fecundity <- read.csv('Fecundity.csv') 

FecundityPlot <- ggplot(Fecundity, aes(x=Group, Sex, y=Fecundity)) + 
    geom_boxplot(fill = fill, color = line) + 
    scale_y_continuous(name = "Fecundity") + 
    #scale_y_continuous(name = "Fecundity", breaks = seq(0, 80, 10), limits=c(0, 80)) + 
    ggtitle("Fecundity") + 
    theme(plot.title = element_text(hjust = 0.5))+ 
    theme_bw(base_size = 11) 

我的数据是这样的:

ID    Group  Sex Generation Fecundity Strain 
ORR-100-M-01 OR-R-100 M 1    0   ORR 
ORR-100-M-02 OR-R-100 M 1    0   ORR 
ORR-100-M-03 OR-R-100 M 1    0   ORR 
JW-100-M-01  JW-100  M 1   13   JW 
JW-100-M-02  JW-100  M 1    0   JW 
JW-100-M-03  JW-100  M 1   114   JW 

我想提出的箱线图与对每个组别及性别酒吧GGPLOT2 。所以在Y轴上会有一个框为Group = OR-R100 Sex = M旁边的OR-R100 F和Fecundity。

此外,我如何手动订购盒子,以便按所需顺序订购OR-R-20,OR-R-40等?

回答

1

您可以在geom_boxplot()之内添加Sex至aes()(颜色,填充,alpha等),ggplot会自动将每组中的女性和男性分开并闪避箱形图,并显示带有性别的图例。

FecundityPlot <- ggplot(Fecundity, aes(x=Group, Sex, y=Fecundity)) + 
         geom_boxplot(aes(fill = Sex)) 

或者,如果你希望所有的y轴的标签,另一种方法是使一个新的列拼接及性别,然后绘制使用的x变量

Fecundity$new.group <- paste(Fecundity$Group, Fecundity Sex) 

FecundityPlot <- ggplot(Fecundity, aes(x=new.group, Sex, y=Fecundity)) + 
         geom_boxplot() 

要为组设置自定义顺序,您需要将组设为一个因子并定义这些级别。在factor()中定义级别的顺序将覆盖字母默认值。

Fecundity$Group <- factor(Fecundity$Group, 
          levels = c("OR-R-20", "OR-R-40", "JW-100")) 
+0

所以这看起来很棒,我喜欢它们是按性别交错的,但是用geom_boxplot(aes(fill = Sex)),我会如何手动为每个性别着色?我可以做一个更简单的boxplot,而不是像这样交错,但是我可以为M和F指定一个颜色吗? – user974887

+0

如果您不喜欢默认颜色,可以使用'scale_fill_manual()'指定颜色。我建议你看看[ggplot2文档](http://ggplot2.tidyverse.org/reference/scale_manual.html)了解这个和其他情节外观定制的细节 –

0

这里的(使用dplyr/tidyverse管道)的一种方法:

Fecundity %>% 
mutate(Group_sex = paste(Group, Sex)) %>% 
ggplot(aes(x = Group_sex, y = Fecundity)) + 
geom_boxplot() 

使用stringsAsFactors = FALSEread.csv通话,或者更好的是,使用来自tidyverse更快read_csv

要设置条形图的顺序,您可以在第一个变异后使用mutate(Group_sex = factor(Group_sex, levels = c(...))) %>%行,并在...(如果不同组合的数量很小)中提供明确的顺序。

+0

我得到一个错误:映射必须由'AES创建()'或'AES _()' – user974887

+0

忘了'ggplot'的'aes'。增加了 –

+0

仍然因为某种原因得到它。直接复制 – user974887

相关问题