分享

R语言 分组箱式图

 世上无难事bio 2022-12-05 发布于湖南

原图:

Whole-genome resequencing of 445 Lactuca accessions reveals the domestication history of cultivated lettuce


复现图以及code:

library(ggplot2)
library(stringr)
library(ggprism)

# 数据处理
x_level<-paste(df$Group1,df$Group2,sep="_")
x_level
df1$group<-str_sub(df1$new_col,5,7)
df1$new_col<-factor(df1$new_col,
                    levels = x_level)

ggplot(df1,aes(x=new_col,y=value))+
  stat_boxplot(geom = "errorbar",width=0.2)+
  geom_boxplot(outlier.shape = 1,aes(fill=group), show.legend = F)+
  scale_fill_manual(values = c("#e64b35","#4daf4a","#4dbbd5","#cab2d6",
                               "#b2df8a"))+
  scale_x_discrete(labels=str_sub(x_level,1,3),guide = "prism_offset")+
  scale_y_continuous(limits = c(-0.021,0.085),
                     breaks = seq(-0.02,0.08,by=0.02))+
  theme_prism(axis_text_angle = 90,base_line_size = 0.1,
              base_fontface = "plain",base_family = "serif")+
  labs(x=NULL, y=expression(paste(italic("D")," statistic")))+
  theme(plot.margin = unit(c(0.2,0.2,2,0.2),'cm'))+
  
  # 加上下方的5条线段
  geom_segment(x=1,xend=5,y=-0.04,yend=-0.04)+
  annotate("text",x=3,y=-0.02,label="CAU",vjust=10)+
  geom_segment(x=6,xend=9,y=-0.04,yend=-0.04)+
  annotate("text",x=7.5,y=-0.02,label="SEU",vjust=10)+
  geom_segment(x=10,xend=12,y=-0.04,yend=-0.04)+
  annotate("text",x=11.5,y=-0.02,label="WEU",vjust=10)+
  geom_segment(x=13,xend=14,y=-0.04,yend=-0.04)+
  annotate("text",x=13.5,y=-0.02,label="EEU",vjust=10)+
  geom_segment(x=14.5,xend=15.5,y=-0.04,yend=-0.04)+
  annotate("text",x=15,y=-0.02,label="WAS",vjust=10)+
  # 加上P1 P2
  annotate("text",x=1,y=-0.02,label="P1",hjust=2,vjust=5)+
  annotate("text",x=1,y=-0.02,label="P2", hjust=2,vjust=10)+
  # 画图后调整坐标轴,可以通过xlim和expand参数调整x轴坐标轴
  coord_cartesian(clip = "off")

学习完代码,发现其实是fill和映射的x不一致,给人的感觉就是一张图里根据fill分了大组然后根据 x细分了小组。很赞。

跟着Nature Genetics 学画图:R语言ggplot2画箱线图(boxplot)展示D statistic

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多