利用R语言ggplot2复现Nature期刊论文图表

箱线图和小提琴图

闫明

南京林业大学

2022-07-15

复现代码

dfToPlot<-read.csv("dfToPlot.csv")
head(dfToPlot)
##     BC_Spec    BC_PWY     BC_VF   BC_CARD RELATIONSHIP.0 COHAB
## 1 0.5018598 0.1521802 0.8009368 0.7540197       RND.PAIR FALSE
## 2 0.6017878 0.1199416 0.9098667 0.6745180       RND.PAIR FALSE
## 3 0.6943654 0.1322052 0.8794888 0.4336659       PARTNERS  TRUE
## 4 0.5504249 0.1195811 0.5355828 0.7883583       RND.PAIR FALSE
## 5 0.8220028 0.3994575 0.8408817 0.9276368         PAR_CH  TRUE
## 6 0.7683990 0.3743061 0.9730157 0.9912979       RND.PAIR FALSE
dfToPlot$RELATIONSHIP.0 <- factor(dfToPlot$RELATIONSHIP.0,
                                  levels=c("RND.PAIR","PARTNERS","PARENT_CHILD","SIBLINGS"))

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.0.5
ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_boxplot()

ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_jitter()

ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_violin()

library(ggplot2)
ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_boxplot() -> p1

p1

ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_jitter() -> p2
p2

ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_violin() -> p3
p3

library(patchwork)
p1 + theme(legend.position = "none") + 
  p2 + theme(legend.position = "none") +
  p3 + theme(legend.position = "none")

cbPalette <- c("#E69F00", "#CC79A7", "#56B4E9", "#009E73", "#CC79A7", "#F0E442", "#999999","#0072B2","#D55E00")
ggplot(data=dfToPlot,aes(x=RELATIONSHIP.0,
                         y=BC_Spec,
                         color=RELATIONSHIP.0))+
  geom_jitter(alpha=0.2,
              position=position_jitterdodge(jitter.width = 0.35, 
                                            jitter.height = 0, 
                                            dodge.width = 0.8))+
  geom_boxplot(alpha=0.2,width=0.45,
               position=position_dodge(width=0.8),
               size=0.75,outlier.colour = NA)+
  geom_violin(alpha=0.2,width=0.9,
              position=position_dodge(width=0.8),
              size=0.75)+
  scale_color_manual(values = cbPalette)+
  theme_classic() +
  theme(legend.position="none") + 
  theme(text = element_text(size=16)) + 
  #ylim(0.0,1.3)+
  ylab("Bray-Curtis distance of Species")