繁体   English   中英

如何使用ggplot2在x轴上绘制两列?

[英]How do I graph two columns on the x axis with ggplot2?

我正在使用以下代码制作箱形图:

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制作一个箱形图,其中每个组和性别都有一个栏。 因此,在OR-R100 F(Y轴上有力)旁边将有一个Group = OR-R100 Sex = M的框。

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

您可以在geom_boxplot() )内的任何aes() (颜色,填充,alpha等)中添加性别,并且ggplot会自动将每个组中的雌性和雄性分开,并躲避方框图,并显示带有性的图例。

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

或者,如果您希望所有标签都位于y轴上,则另一种方法是创建一个新的列,以将group和sex连接在一起,然后将其用作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"))

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

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

使用stringsAsFactors = FALSEread.csv通话,或者更好的是,使用更快read_csvtidyverse

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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