美文网首页ggplot2绘图
R 语言 | 堆积图绘制教程|收藏

R 语言 | 堆积图绘制教程|收藏

作者: 小杜的生信筆記 | 来源:发表于2022-01-21 18:16 被阅读0次

    堆积图

    堆积图

    PS:如果你需要本教程的练习代码和数据,可以在公众号回复“20220121”即可获得。


    绘图

    ## date: 2022.0121
    ## author:小杜的生信筆記
    # 堆积图
    
    rm(list = ls())
    library("ggplot2")</pre>
    

    导入数据

    decoration-color: initial;">setwd("D:\\小杜的生信筆記\\堆积图")
    df <- read.table("input_data.txt", header = T)
    head(df)</pre>
    
    > head(df)
     number   Type Treatment
    1    142  mRNAs   Treat01
    2    246 miRNAs   Treat01
    3    464  mRNAs   Treat02
    4    235 miRNAs   Treat02
    5    363  mRNAs   Treat03
    6    536 miRNAs   Treat03</pre>
    

    作图

    基础图形

    ggplot(df, 
     aes(y= Treatment, x = number, fill = Type))+ ## 使用ggplot2语法
     geom_bar(stat = "identity", position = "stack", color = "black",width = 0.8) ## 添加柱子
    

    对图形美化

    这个颜色的配置是我比较喜欢的颜色,如果你喜欢其他颜色,也可以自己进行配置
    `palette =`  `Set1`至`Set**`,`Greens`,`Accent,自己根据其选择吧。
    
    ggplot(df, 
     aes(y= Treatment, x = number, fill = Type))+ ## 使用ggplot2语法
     geom_bar(stat = "identity", position = "stack", color = "black",width = 0.8)+  ## 添加柱子
     theme_bw()+
     scale_fill_brewer(palette = "Accent")   ## 添加柱子颜色,个人非常喜欢这个配置的颜色
    

    去掉方框

    ggplot(df, 
     aes(y= Treatment, x = number, fill = Type))+ ## 使用ggplot2语法
     geom_bar(stat = "identity", position = "stack", color = "black",width = 0.8)+  ## 添加柱子
     theme_bw()+
     scale_fill_brewer(palette = "Accent")+  ## 添加柱子颜色,个人非常喜欢这个配置的颜色
     theme_classic()+
     theme(legend.title=element_blank())
    

    调整柱子距离X轴和Y轴的距离

    ## 添加下面的吗即可
    scale_x_continuous(expand = c(0.05,0))+  ## 限制x轴坐标的距离y轴的距离
     theme(text = element_text(size=15),  ## y轴字体大小
     legend.position = c(0.8,0.4))+  #theme(legend.position='none') 不要主题##; theme(legend.position = c(0.8,0.4)) 调节位置
    

    更改X轴和y轴的字体,颜色,大小

    theme(axis.text.x = element_text(face =  "bold", color = "black", size = 12),
     axis.text = element_text(colour = "black", size = 15)
    
    ### 
    face = : 字体
    color = : 颜色
    size = : 字体大小</pre>
    

    更改X轴和y轴的坐标

     ylab("")+xlab("Number of **")+  ## 添加x轴坐标</pre>
    

    更改或添加标题

      ## 添加标题
     theme(plot.title = element_text(hjust = 0.5, size = 12)) ##标题的调节</pre>
    

    出图


    “小杜的生信筆記” 公众号知乎简书平台,主要发表或收录生物信息学的教程,以及基于R的分析和可视化(包括数据分析,图形绘制等);分享感兴趣的文献和学习资料!

    相关文章

      网友评论

        本文标题:R 语言 | 堆积图绘制教程|收藏

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