美文网首页绘图技巧R plot
跟着Cell学作图:R语言ggplot2做蜂群图的简单小例子

跟着Cell学作图:R语言ggplot2做蜂群图的简单小例子

作者: 小明的数据分析笔记本 | 来源:发表于2021-09-27 10:36 被阅读0次

    论文

    https://www.sciencedirect.com/science/article/pii/S0092867421008916#da0010

    Ancient and modern genomes unravel the evolutionary history of the rhinoceros family

    image.png

    犀牛

    本地论文 1-s2.0-S0092867421008916-main.pdf

    数据和代码下载链接

    https://github.com/liushanlin/rhinoceros-comparative-genome

    今天的推文我们来重复一下论文中的 Figure3A

    image.png

    论文里提供的代码是使用ggplot2的扩展包ggbeeswarm

    首先是读入数据

    ht = read.table("heterCombined.txt1")
    head(ht)
    unique(ht$V1)
    
    • head()函数是查看数据集的前六行
    image.png
    • unique()函数是查看一组数据中有多少中元素,可以用来去重复
      比如一个向量c(1,1,2,2,2,3,3,3,3)
    unique(c(1,1,2,2,2,3,3,3))
    
    image.png

    加载需要用到的R包

    library(ggplot2)
    library(scales)
    #install.packages("ggbeeswarm")
    library(ggbeeswarm)
    

    这里用到的是scales包里的percent()函数,可以把小数转换为百分数
    比如

    scales::percent(0.05)
    
    image.png

    最基本的蜂群图

    plot = ggplot(data = ht, 
                  aes(x=V1, y=round(V4,4), 
                      fill = V6, shape=V5))+ 
      geom_beeswarm(cex=1.5,
                    size=2.5,
                    priority = "density") + 
      scale_shape_manual(values = c(21,22))
    
    plot
    
    image.png

    这里有一个问题是fill映射颜色,为什么图例没有颜色呢?

    对Y坐标轴进行一些设置

    plota = plot + 
      scale_y_continuous(limits = c(0,0.01),
                         name = "heterozygosity", 
                         expand = c(0.0001,0.0001),
                         labels = scales::percent) + 
      labs(fill="",shape="")
    
    plota
    
    image.png

    对X坐标轴进行一些设置和手动更改填充颜色

    plotb = plota + 
      scale_fill_manual(values = c("#E69F00", "#999999"))+ 
      scale_x_discrete(name = "", 
                       limits=c("animals", "mammals",
                                "ruminants","rhinoceros"))
    
    plotb
    
    image.png

    最后是对主题进行一些设置

    plotc = plotb + theme(panel.background = element_blank(),
                        panel.grid = element_blank(),
                        axis.line.x = element_line(),
                        axis.line.y = element_line(),
                        legend.position = "top",
                        axis.text = element_text(size = 12))
    plotc
    
    image.png

    论文里提供的代码到这里就结束了,但是这个图和论文中实际用到的图还是有很多不一样的地方的,可能是出图后用其他软件编辑的吧

    这里有一个疑问是为啥用fill参数映射颜色图例却没有显示颜色呢?

    大家有知道的吗?欢迎留言指出!

    示例数据和代码可以直接到论文中提供的下载链接去下载,或者直接在公众号后台留言20210927获取(注意是精确匹配开头结尾都不能有空格)

    欢迎大家关注我的公众号

    小明的数据分析笔记本

    小明的数据分析笔记本 公众号 主要分享:1、R语言和python做数据分析和数据可视化的简单小例子;2、园艺植物相关转录组学、基因组学、群体遗传学文献阅读笔记;3、生物信息学入门学习资料及自己的学习笔记!

    相关文章

      网友评论

        本文标题:跟着Cell学作图:R语言ggplot2做蜂群图的简单小例子

        本文链接:https://www.haomeiwen.com/subject/zwnzwltx.html