R可视化:ggpubr包学习

欢迎大家关注全网生信学习者系列:

  • WX公zhong号:生信学习者

  • Xiao hong书:生信学习者

  • 知hu:生信学习者

  • CDSN:生信学习者2

介绍

ggpubr是我经常会用到的R包,它傻瓜式的画图方式对很多初次接触R绘图的人来讲是很友好的。该包有个stat_compare_means函数可以做组间假设检验分析。

安装R包

install.packages("ggpubr")
devtools::devtools::install_github("kassambara/ggpubr")
library(ggpubr)
​
​
plotdata <- data.frame(sex = factor(rep(c("F", "M"), each=200)),weight = c(rnorm(200, 55), rnorm(200, 58)))

密度图density

ggdensity(plotdata, x = "weight",add = "mean", rug = TRUE,    # x轴显示分布密度color = "sex", fill = "sex",palette = c("#00AFBB", "#E7B800"))

柱状图histogram

gghistogram(plotdata, x = "weight",bins = 30,add = "mean", rug = TRUE,color = "sex", fill = "sex",palette = c("#00AFBB", "#E7B800"))

箱线图boxplot

df <- ToothGrowth
head(df)
my_comparisons <- list( c("0.5", "1"), c("1", "2"), c("0.5", "2") )
ggboxplot(df, x = "dose", y = "len",color = "dose", palette =c("#00AFBB", "#E7B800", "#FC4E07"),add = "jitter", shape = "dose")+stat_compare_means(comparisons = my_comparisons)+ # Add pairwise comparisons p-valuestat_compare_means(label.y = 50) 

小提琴图violin

ggviolin(df, x = "dose", y = "len", fill = "dose",palette = c("#00AFBB", "#E7B800", "#FC4E07"),add = "boxplot", add.params = list(fill = "white"))+stat_compare_means(comparisons = my_comparisons, label = "p.signif")+ # Add significance levelsstat_compare_means(label.y = 50)  

点图dotplot

ggdotplot(ToothGrowth, x = "dose", y = "len",color = "dose", palette = "jco", binwidth = 1)

有序条形图 ordered bar plots

data("mtcars")
dfm <- mtcars
dfm$cyl <- as.factor(dfm$cyl)
dfm$name <- rownames(dfm)
head(dfm[, c("name", "wt", "mpg", "cyl")])
​
ggbarplot(dfm, x = "name", y = "mpg",fill = "cyl",               # change fill color by cylcolor = "white",            # Set bar border colors to whitepalette = "jco",            # jco journal color palett. see ?ggparsort.val = "asc",           # Sort the value in dscending ordersort.by.groups = TRUE,      # Sort inside each groupx.text.angle = 90)          # Rotate vertically x axis texts

偏差图Deviation graphs

dfm$mpg_z <- (dfm$mpg -mean(dfm$mpg))/sd(dfm$mpg)
dfm$mpg_grp <- factor(ifelse(dfm$mpg_z < 0, "low", "high"), levels = c("low", "high"))
# Inspect the data
head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")])
​
ggbarplot(dfm, x = "name", y = "mpg_z",fill = "mpg_grp",           # change fill color by mpg_levelcolor = "white",            # Set bar border colors to whitepalette = "jco",            # jco journal color palett. see ?ggparsort.val = "asc",           # Sort the value in ascending ordersort.by.groups = FALSE,     # Don't sort inside each groupx.text.angle = 90,          # Rotate vertically x axis textsylab = "MPG z-score",rotate = FALSE,xlab = FALSE,legend.title = "MPG Group")

棒棒糖图 lollipop chart

ggdotchart(dfm, x = "name", y = "mpg",color = "cyl",                                # Color by groupspalette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palettesorting = "descending",                       # Sort value in descending orderadd = "segments",                             # Add segments from y = 0 to dotsrotate = TRUE,                                # Rotate verticallygroup = "cyl",                                # Order by groupsdot.size = 6,                                 # Large dot sizelabel = round(dfm$mpg),                       # Add mpg values as dot labelsfont.label = list(color = "white", size = 9, vjust = 0.5),               # Adjust label parametersggtheme = theme_pubr())                       # ggplot2 theme

偏差图Deviation graph

ggdotchart(dfm, x = "name", y = "mpg_z",color = "cyl",                                # Color by groupspalette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palettesorting = "descending",                       # Sort value in descending orderadd = "segments",                             # Add segments from y = 0 to dotsadd.params = list(color = "lightgray", size = 2), # Change segment color and sizegroup = "cyl",                                # Order by groupsdot.size = 6,                                 # Large dot sizelabel = round(dfm$mpg_z,1),                   # Add mpg values as dot labelsfont.label = list(color = "white", size = 9, vjust = 0.5),               # Adjust label parametersggtheme = theme_pubr())+                      # ggplot2 themegeom_hline(yintercept = 0, linetype = 2, color = "lightgray")

散点图scatterplot

df <- datasets::iris
head(df)
ggscatter(df, x = 'Sepal.Width', y = 'Sepal.Length', palette = 'jco', shape = 'Species', add = 'reg.line',color = 'Species', conf.int = TRUE)

  • 添加回归线的系数

ggscatter(df, x = 'Sepal.Width', y = 'Sepal.Length', palette = 'jco', shape = 'Species', add = 'reg.line',color = 'Species', conf.int = TRUE)+stat_cor(aes(color=Species),method = "pearson", label.x = 3)

  • 添加聚类椭圆 concentration ellipses

data("mtcars")
dfm <- mtcars
dfm$cyl <- as.factor(dfm$cyl)
dfm$name <- rownames(dfm)
​
p1 <- ggscatter(dfm, x = "wt", y = "mpg",color = "cyl", palette = "jco",shape = "cyl",ellipse = TRUE)
p2 <- ggscatter(dfm, x = "wt", y = "mpg",color = "cyl", palette = "jco",shape = "cyl",ellipse = TRUE,ellipse.type = "convex")
cowplot::plot_grid(p1, p2, align = "hv", nrow = 1)

  • 添加mean和stars

ggscatter(dfm, x = "wt", y = "mpg",color = "cyl", palette = "jco",shape = "cyl",ellipse = TRUE, mean.point = TRUE,star.plot = TRUE)

  • 显示点标签

dfm$name <- rownames(dfm)
p3 <- ggscatter(dfm, x = "wt", y = "mpg",color = "cyl", palette = "jco",label = "name",repel = TRUE)
p4 <- ggscatter(dfm, x = "wt", y = "mpg",color = "cyl", palette = "jco",label = "name",repel = TRUE,label.select = c("Toyota Corolla", "Merc 280", "Duster 360"))
cowplot::plot_grid(p3, p4, align = "hv", nrow = 1)

气泡图bubble plot

ggscatter(dfm, x = "wt", y = "mpg",color = "cyl",palette = "jco",size = "qsec", alpha = 0.5)+scale_size(range = c(0.5, 15))    # Adjust the range of points size

连线图 lineplot

p1 <- ggbarplot(ToothGrowth, x = "dose", y = "len", add = "mean_se",color = "supp", palette = "jco", position = position_dodge(0.8))+stat_compare_means(aes(group = supp), label = "p.signif", label.y = 29)
p2 <- ggline(ToothGrowth, x = "dose", y = "len", add = "mean_se",color = "supp", palette = "jco")+stat_compare_means(aes(group = supp), label = "p.signif", label.y = c(16, 25, 29))
cowplot::plot_grid(p1, p2, ncol = 2, align = "hv")

添加边沿图 marginal plots

library(ggExtra)
p <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",color = "Species", palette = "jco",size = 3, alpha = 0.6)
ggMarginal(p, type = "boxplot")

  • 第二种添加方式: 分别画出三个图,然后进行组合

sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",color = "Species", palette = "jco",size = 3, alpha = 0.6, ggtheme = theme_bw())             
​
xplot <- ggboxplot(iris, x = "Species", y = "Sepal.Length", color = "Species", fill = "Species", palette = "jco",alpha = 0.5, ggtheme = theme_bw())+ rotate()
​
yplot <- ggboxplot(iris, x = "Species", y = "Sepal.Width",color = "Species", fill = "Species", palette = "jco",alpha = 0.5, ggtheme = theme_bw())
​
​
sp <- sp + rremove("legend")
yplot <- yplot + clean_theme() + rremove("legend")
xplot <- xplot + clean_theme() + rremove("legend")
cowplot::plot_grid(xplot, NULL, sp, yplot, ncol = 2, align = "hv", rel_widths = c(2, 1), rel_heights = c(1, 2))

  • 上图主图和边沿图之间的space太大,第三种方法能克服这个缺点

library(cowplot) 
# Main plot
pmain <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))+geom_point()+ggpubr::color_palette("jco")
​
# Marginal densities along x axis
xdens <- axis_canvas(pmain, axis = "x")+geom_density(data = iris, aes(x = Sepal.Length, fill = Species),alpha = 0.7, size = 0.2)+ggpubr::fill_palette("jco")
​
# Marginal densities along y axis
# Need to set coord_flip = TRUE, if you plan to use coord_flip()
ydens <- axis_canvas(pmain, axis = "y", coord_flip = TRUE)+geom_boxplot(data = iris, aes(x = Sepal.Width, fill = Species),alpha = 0.7, size = 0.2)+coord_flip()+ggpubr::fill_palette("jco")
​
p1 <- insert_xaxis_grob(pmain, xdens, grid::unit(.2, "null"), position = "top")
p2 <- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right")
ggdraw(p2)

  • 第四种方法,通过grob设置

# Scatter plot colored by groups ("Species")
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",color = "Species", palette = "jco",size = 3, alpha = 0.6)
# Create box plots of x/y variables
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Box plot of the x variable
xbp <- ggboxplot(iris$Sepal.Length, width = 0.3, fill = "lightgray") +rotate() +theme_transparent()
# Box plot of the y variable
ybp <- ggboxplot(iris$Sepal.Width, width = 0.3, fill = "lightgray") +theme_transparent()
# Create the external graphical objects
# called a "grop" in Grid terminology
xbp_grob <- ggplotGrob(xbp)
ybp_grob <- ggplotGrob(ybp)
# Place box plots inside the scatter plot
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
xmin <- min(iris$Sepal.Length); xmax <- max(iris$Sepal.Length)
ymin <- min(iris$Sepal.Width); ymax <- max(iris$Sepal.Width)
yoffset <- (1/15)*ymax; xoffset <- (1/15)*xmax
# Insert xbp_grob inside the scatter plot
sp + annotation_custom(grob = xbp_grob, xmin = xmin, xmax = xmax, ymin = ymin-yoffset, ymax = ymin+yoffset) +# Insert ybp_grob inside the scatter plotannotation_custom(grob = ybp_grob,xmin = xmin-xoffset, xmax = xmin+xoffset, ymin = ymin, ymax = ymax)

二维密度图 2d density

sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",color = "lightgray")
p1 <- sp + geom_density_2d()
# Gradient color
p2 <- sp + stat_density_2d(aes(fill = ..level..), geom = "polygon")
# Change gradient color: custom
p3 <- sp + stat_density_2d(aes(fill = ..level..), geom = "polygon")+gradient_fill(c("white", "steelblue"))
# Change the gradient color: RColorBrewer palette
p4 <- sp + stat_density_2d(aes(fill = ..level..), geom = "polygon") +gradient_fill("YlOrRd")
​
cowplot::plot_grid(p1, p2, p3, p4, ncol = 2, align = "hv")

混合图

混合表、字体和图

# Density plot of "Sepal.Length"
#::::::::::::::::::::::::::::::::::::::
density.p <- ggdensity(iris, x = "Sepal.Length", fill = "Species", palette = "jco")
# Draw the summary table of Sepal.Length
#::::::::::::::::::::::::::::::::::::::
# Compute descriptive statistics by groups
stable <- desc_statby(iris, measure.var = "Sepal.Length",grps = "Species")
stable <- stable[, c("Species", "length", "mean", "sd")]
# Summary table plot, medium orange theme
stable.p <- ggtexttable(stable, rows = NULL, theme = ttheme("mOrange"))
# Draw text
#::::::::::::::::::::::::::::::::::::::
text <- paste("iris data set gives the measurements in cm","of the variables sepal length and width","and petal length and width, respectively,","for 50 flowers from each of 3 species of iris.","The species are Iris setosa, versicolor, and virginica.", sep = " ")
text.p <- ggparagraph(text = text, face = "italic", size = 11, color = "black")
# Arrange the plots on the same page
ggarrange(density.p, stable.p, text.p, ncol = 1, nrow = 3,heights = c(1, 0.5, 0.3))

  • 注释table在图上

density.p <- ggdensity(iris, x = "Sepal.Length", fill = "Species", palette = "jco")
​
stable <- desc_statby(iris, measure.var = "Sepal.Length",grps = "Species")
stable <- stable[, c("Species", "length", "mean", "sd")]
stable.p <- ggtexttable(stable, rows = NULL, theme = ttheme("mOrange"))
density.p + annotation_custom(ggplotGrob(stable.p),xmin = 5.5, ymin = 0.7,xmax = 8)

systemic information

sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)
​
Matrix products: default
​
locale:
[1] LC_COLLATE=Chinese (Simplified)_China.936  LC_CTYPE=Chinese (Simplified)_China.936   
[3] LC_MONETARY=Chinese (Simplified)_China.936 LC_NUMERIC=C                              
[5] LC_TIME=Chinese (Simplified)_China.936    
​
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     
​
other attached packages:
[1] ggpubr_0.4.0  ggplot2_3.3.2
​
loaded via a namespace (and not attached):[1] zip_2.0.4         Rcpp_1.0.3        cellranger_1.1.0  pillar_1.4.6      compiler_3.6.1    forcats_0.5.0    [7] tools_3.6.1       digest_0.6.27     lifecycle_0.2.0   tibble_3.0.4      gtable_0.3.0      pkgconfig_2.0.3  
[13] rlang_0.4.8       openxlsx_4.2.3    ggsci_2.9         rstudioapi_0.10   curl_4.3          haven_2.3.1      
[19] rio_0.5.16        withr_2.1.2       dplyr_1.0.2       generics_0.0.2    vctrs_0.3.4       hms_0.5.3        
[25] grid_3.6.1        tidyselect_1.1.0  glue_1.4.2        data.table_1.13.2 R6_2.4.1          rstatix_0.6.0    
[31] readxl_1.3.1      foreign_0.8-73    carData_3.0-4     farver_2.0.3      tidyr_1.0.0       purrr_0.3.3      
[37] car_3.0-10        magrittr_1.5      scales_1.1.0      backports_1.1.10  ellipsis_0.3.1    abind_1.4-5      
[43] colorspace_1.4-1  ggsignif_0.6.0    labeling_0.4.2    stringi_1.4.3     munsell_0.5.0     broom_0.7.2      
[49] crayon_1.3.4

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/27258.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

提升你的编程体验:自定义 PyCharm 背景图片

首先&#xff0c;打开 PyCharm 的设置菜单&#xff0c;点击菜单栏中的 File > Settings 来访问设置&#xff0c;也可以通过快捷键 CtrlAItS 打开设置。 然后点击Appearance & Behavior > Appearance。 找到Background image...左键双击进入。 Image:传入自己需要设置…

常见的 EVM 版本以及它们的区别

EVM&#xff08;以太坊虚拟机&#xff09;版本的演进是为了引入新的特性和改进以太坊平台的安全性、效率和功能性。每个版本通常伴随着以太坊网络的硬分叉&#xff0c;这是以太坊协议的重大升级。以下是一些常见的EVM版本及其主要区别&#xff1a; Homestead (2016年3月)&…

中国首台!紧随美国,重磅发布100比特中性原子量子计算机

2024年6月11日上午&#xff0c;“武汉量子论坛—2024”隆重开幕&#xff0c;国家自然科学基金委员会主任窦贤康院士&#xff0c;武汉大学校长张平文院士&#xff0c;以及叶朝辉、徐红星、祝世宁等院士出席大会。在会议上&#xff0c;中科酷原重磅发布国内首台原子量子计算机——…

利用 HTML5 Canvas 实现在线签字功能

目录 前言 一、HTML5 Canvas 简介 二、签字功能的实现 效果演示 完整代码 前言 在现代互联网应用中&#xff0c;有时我们需要让用户在网页上进行签字操作&#xff0c;比如确认文件、填写电子表格或者签署合同。利用 HTML5 的 canvas 画布&#xff0c;我们可以轻松地实现这一…

图片转Base64

在Python中, 可以使用内置的base64模块以及图像处理库(如PIL, 也称为Pillow)来将图片转换为Base64编码的字符串. 以下是一个简单的示例, 说明如何实现这一过程:首先, 需要安装Pillow库(如果尚未安装), 可以使用pip来安装: pip install pillow然后, 可以使用以下Python代码将图片…

RabbitMQ实践——交换器(Exchange)和绑定(Banding)

大纲 direct型交换器默认交换器命名交换器 fanout型交换器topic型交换器headers型交换器 RabbitMQ在概念上由三部分组成&#xff1a; 交换器&#xff08;Exchange&#xff09;&#xff1a;负责接收消息发布者发布消息的结构&#xff0c;同时它会根据“绑定关系”&#xff08;Ba…

基于SpringBoot+VueBBS论坛系统设计和实现(源码+LW+调试文档+讲解等)

&#x1f497;博主介绍&#xff1a;✌全网粉丝1W,CSDN作者、博客专家、全栈领域优质创作者&#xff0c;博客之星、平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌&#x1f497; &#x1f31f;文末获取源码数据库&#x1f31f; 感兴趣的可以先收藏起来&#xff0c;还…

sku与spu的区别!!!

一个 SPU 可以有多个 SKU。

攻防演练之-成功的钓鱼邮件溯源

书接上文&#xff0c;《网络安全攻防演练风云》专栏之攻防演练之-网络安全产品大巡礼二&#xff0c;这里。 演练第一天并没有太大的波澜&#xff0c;白天的时间过得很快。夜色降临&#xff0c;攻防演练中心内的灯光依旧明亮。对于网络安全团队来说&#xff0c;夜晚和白天并没有…

教育培训知识付费在线课程小程序开发

教育培训知识付费在线课程小程序功能概述 核心功能 课程报名与缴费&#xff1a;支持线上报名、缴费&#xff0c;自定义课程时间、人数等。 砍价功能&#xff1a;用户通过分享邀请好友参与砍价&#xff0c;享受低价购买课程的优惠。 视频课程&#xff1a;支持倍速播放&#x…

Linux 基本指令3

date指令 date[选项][格式] %Y--年 %m--月 %d--日 %H--小时 %M--分 %S--秒 中间可用其他符号分割&#xff0c;不能使用空格。 -s 设置时间&#xff0c;会返回设置时间的信息并不是改变当前时间 设置全部时间年可用-或者&#xff1a;分割日期和时间用空格分隔&#xff…

Qt创建静态库及静态库使用

Qt创建静态库及静态库使用 1. 创建一个库文件 选择静态库 将需要打包的.h 和.cpp文件添加到程序中&#xff0c; 在编译器版本下的debug和release模式下分别编译&#xff08;右键项目&#xff0c;点击“qmake”,再点击“构建”&#xff09;后&#xff0c;在对应的的build目录下…

“探索机器学习的多面世界:从理论到应用与未来展望“

博客主页&#xff1a;誓则盟约系列专栏&#xff1a;机器学习 专栏关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ 目录 一、机器学习基础理论 1.机器学习的定义与分类 监督学习 无监督学…

Python数据分析与机器学习在医疗诊断中的应用

文章目录 &#x1f4d1;引言一、数据收集与预处理1.1 数据收集1.2 数据预处理 二、特征选择与构建2.1 特征选择2.2 特征构建 三、模型选择与训练3.1 逻辑回归3.2 随机森林3.3 深度学习 四、模型评估与调优4.1 交叉验证4.2 超参数调优 五、模型部署与应用5.1 模型保存与加载5.2 …

Python:从头创建 Asyncio (2)

引言 现在&#xff0c;asyncio 已成为 Python 社区中的热门话题&#xff0c;并且名副其实——它提供了一种非常出色的处理 I/O 密集型程序的方法&#xff01;在我探索 asyncio 的过程中&#xff0c;我起初并不太明白它的工作原理。但随着深入学习&#xff0c;我意识到 asyncio …

Java 反射机制 -- Java 语言反射的概述、核心类与高级应用

大家好,我是栗筝i,这篇文章是我的 “栗筝i 的 Java 技术栈” 专栏的第 010 篇文章,在 “栗筝i 的 Java 技术栈” 这个专栏中我会持续为大家更新 Java 技术相关全套技术栈内容。专栏的主要目标是已经有一定 Java 开发经验,并希望进一步完善自己对整个 Java 技术体系来充实自…

GitLab教程(二):快速上手Git

文章目录 1.将远端代码克隆到本地2.修改本地代码并提交到远程仓库3.Git命令总结git clonegit statusgit addgit commitgit pushgit log 首先&#xff0c;我在Gitlab上创建了一个远程仓库&#xff0c;用于演示使用Gitlab进行版本管理的完整流程&#xff1a; 1.将远端代码克隆到本…

导出 Whisper 模型到 ONNX

前言 在语音识别领域&#xff0c;Whisper 模型因其出色的性能和灵活性备受关注。为了在更多平台和环境中部署 Whisper 模型&#xff0c;导出为 ONNX 格式是一个有效的途径。ONNX&#xff08;Open Neural Network Exchange&#xff09;是一个开放格式&#xff0c;支持不同的深度…

吴恩达2022机器学习专项课程C2W3:2.25 理解方差和偏差(诊断方差偏差正则化偏差方案搭建性能学习曲线)

目录 引言名词替代影响模型偏差和方差的因素1.多项式阶数2.正则化参数 判断是否有高偏差或高方差1.方法一&#xff1a;建立性能基准水平2.方法二&#xff1a;建立学习曲线 总结 引言 机器学习系统开发的典型流程是从一个想法开始&#xff0c;然后训练模型。初次训练的结果通常…