使用 ggpubr 包制图

简介: 使用 ggpubr 包制图

简介

Hadley Wickham撰写的ggplot2[1]是好用的软件包,是可视化工具的必备包。但是,需要知道ggplot2一定的理论与原理,对新手来说,入门门槛还是比较高的。

ggpubr软件包提供了一些易于使用的功能,基于ggplot2编写,语法十分简单的的图标。对于一些刚了解R语言,而想用R做可发表的图表的人来说,这真的太好用了!

下面对该文章ggpubr: Publication Ready Plots[2]进行讲解。

安装

  • 从CRAN安装:
install.packages("ggpubr")
  • 从GitHub安装最新版本:
if(!require(devtools))install.packages("devtools")
devtools :: install_github("kassambara / ggpubr")

可视化函数汇总

图形 命令
密度图 ggdensity()
箱型图 ggboxplot()
柱状图 gghistogram()
小提琴图 ggdotchart()
条形图 ggdotchart()
棒棒图,克利夫兰图 ggdotchart()

密度图

library(ggpubr)
# 构建数据集
set.seed(1234)
wdata = data.frame(
   sex = factor(rep(c("F", "M"), each=200)),
   weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata, 4)

c1683668e55e3d7590d9645d6b4614d9.png


  • 密度图(ggdensity)与平均线(add = "mean");按性别("sex")进行颜色填充;加入边际地毯(rug = TRUE)并使用自定义面板(palette = c("#00AFBB", "#E7B800"))
ggdensity(wdata, x = "weight",
   add = "mean", rug = TRUE,
   color = "sex", fill = "sex",
   palette = c("#00AFBB", "#E7B800"))

974d46cbf2a0a129687cba9b8a2fa4ac.png

下面是绘制柱状图(gghistogram),其他参数和上面类似。

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

8305aa43a8374e786ff43205c6058683.png

箱型图

# Load data
data("ToothGrowth")
df <- ToothGrowth
head(df, 4)


按剂量("dose")进行颜色填充;添加抖动点并按剂量("dose")更改形状。

p <- ggboxplot(df, x = "dose", y = "len",
                color = "dose", palette =c("#00AFBB", "#E7B800", "#FC4E07"),
                add = "jitter", shape = "dose")
 p

4c33afb716a32480058263dcdbd349d7.png

还可以比较不同组均值之间的关系(stat_compare_means(label.y = 50)),并添加p值(stat_compare_means(label.y = 50) )

my_comparisons <- list( c("0.5", "1"), c("1", "2"), c("0.5", "2") )
p + stat_compare_means(comparisons = my_comparisons)+ # Add pairwise comparisons p-value
  stat_compare_means(label.y = 50)                   # Add global p-value

b6751ac9c80607ee2ac2279731e9ea9a.png


小提琴图

下图是小提琴图(ggviolin)与箱型图的结合(add = "boxplot"),按剂量("dose")进行颜色填充;增加白色填充(add.params = list(fill = "white"))的箱型图,并加入各组比较的p值。

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 levels
  stat_compare_means(label.y = 50)                                      # Add global the p-value

15a1a7d68fe8b23cca524d0fd4757644.png

条形图

数据集

这里用mtcars数据集中进行绘制。

data("mtcars")
dfm <- mtcars
dfm$cyl <- as.factor(dfm$cyl)
dfm$name <- rownames(dfm)
head(dfm[, c("name", "wt", "mpg", "cyl")])



有序的条形图

条形图(ggbarplot)中可以利用sort.val = "desc"把数据从大到小排序并且不在组内进行排序(sort.by.groups = FALSE),而是所有数据排序;旋转x轴标签(x.text.angle = 90)。值得一提的是,这里使用了jco杂志的颜色版式(palette = "jco")。

ggbarplot(dfm, x = "name", y = "mpg",
          fill = "cyl",               # change fill color by cyl
          color = "white",            # Set bar border colors to white
          palette = "jco",            # jco journal color palett. see ?ggpar
          sort.val = "desc",          # Sort the value in dscending order
          sort.by.groups = FALSE,     # Don't sort inside each group
          x.text.angle = 90           # Rotate vertically x axis texts
          )

4e8eef992852a123e218e92aa4890e03.png

如果按照组内排序的话(sort.by.groups = TRUE) ,就是下面这样。

ggbarplot(dfm, x = "name", y = "mpg",
          fill = "cyl",               # change fill color by cyl
          color = "white",            # Set bar border colors to white
          palette = "jco",            # jco journal color palett. see ?ggpar
          sort.val = "asc",           # Sort the value in dscending order
          sort.by.groups = TRUE,      # Sort inside each group
          x.text.angle = 90           # Rotate vertically x axis texts
          )

f12ce3dd1f022dbba17460b9e2cbd830.png

偏差图

偏差图显示了定量值与参考值的偏差。在下面的R代码中,我们将绘制来自mtcars数据集的mpgz-score变化(标准化的一种)。

# Calculate the z-score of the mpg data
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"))
head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")])


根据上面的数据,创建一个有序的箱型图,按升序对值排序(sort.val = "asc")。这里和前面箱型图不同的是,使用刚建的mpg_grp变量作为填充参数,而该参数是因子(含两个水平,levels = c("low", "high"))。

ggbarplot(dfm, x = "name", y = "mpg_z",
          fill = "mpg_grp",           # change fill color by mpg_level
          color = "white",            # Set bar border colors to white
          palette = "jco",            # jco journal color palett. see ?ggpar
          sort.val = "asc",           # Sort the value in ascending order
          sort.by.groups = FALSE,     # Don't sort inside each group
          x.text.angle = 90,          # Rotate vertically x axis texts
          ylab = "MPG z-score",
          xlab = FALSE,
          legend.title = "MPG Group"
          )

7c7f41965b15cac2a8596202d22e5d75.png


旋转x,y轴(rotate = TRUE)并进行降序排序(sort.val = “desc”),如下图所示,该图非常美观,可读性很强。

ggbarplot(dfm, x = "name", y = "mpg_z",
          fill = "mpg_grp",           # change fill color by mpg_level
          color = "white",            # Set bar border colors to white
          palette = "jco",            # jco journal color palett. see ?ggpar
          sort.val = "desc",          # Sort the value in descending order
          sort.by.groups = FALSE,     # Don't sort inside each group
          x.text.angle = 90,          # Rotate vertically x axis texts
          ylab = "MPG z-score",
          legend.title = "MPG Group",
          rotate = TRUE,
          ggtheme = theme_minimal()
          )

散点图

棒糖图

棒糖图是条形图的另一种选择,最终图像像棒棒糖一样。

ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                                # Color by groups
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette
           sorting = "ascending",                        # Sort value in descending order
           add = "segments",                             # Add segments from y = 0 to dots
           ggtheme = theme_pubr()                        # ggplot2 theme
           )


ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                                # Color by groups
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette
           sorting = "descending",                       # Sort value in descending order
           add = "segments",                             # Add segments from y = 0 to dots
           rotate = TRUE,                                # Rotate vertically
           group = "cyl",                                # Order by groups
           dot.size = 6,                                 # Large dot size
           label = round(dfm$mpg),                        # Add mpg values as dot labels
           font.label = list(color = "white", size = 9,
                             vjust = 0.5),               # Adjust label parameters
           ggtheme = theme_pubr()                        # ggplot2 theme
           )


偏差图

还是使用上面的数据集,构建棒棒糖系列的偏差图。改变线段的颜色和大小: add.params = list(color = “lightgray”, size = 2)

ggdotchart(dfm, x = "name", y = "mpg_z",
           color = "cyl",                                # Color by groups
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette
           sorting = "descending",                       # Sort value in descending order
           add = "segments",                             # Add segments from y = 0 to dots
           add.params = list(color = "lightgray", size = 2), # Change segment color and size
           group = "cyl",                                # Order by groups
           dot.size = 6,                                 # Large dot size
           label = round(dfm$mpg_z,1),                        # Add mpg values as dot labels
           font.label = list(color = "white", size = 9,
                             vjust = 0.5),               # Adjust label parameters
           ggtheme = theme_pubr()                        # ggplot2 theme
           )+
  geom_hline(yintercept = 0, linetype = 2, color = "lightgray")


克利夫兰散点图

在前面的基础上,只要加入以下代码即可得到克利夫兰散点图(theme_cleveland())。

ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                                # Color by groups
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette
           sorting = "descending",                       # Sort value in descending order
           rotate = TRUE,                                # Rotate vertically
           dot.size = 2,                                 # Large dot size
           y.text.col = TRUE,                            # Color y text by groups
           ggtheme = theme_pubr()                        # ggplot2 theme
           )+
  theme_cleveland()                                      # Add dashed grids

参考资料

[1]

ggplot2: https://ggplot2.tidyverse.org/

[2]

ggpubr: Publication Ready Plots: http://www.sthda.com/english/articles/24-ggpubr-publication-ready-plots/

相关实践学习
在云上部署ChatGLM2-6B大模型(GPU版)
ChatGLM2-6B是由智谱AI及清华KEG实验室于2023年6月发布的中英双语对话开源大模型。通过本实验,可以学习如何配置AIGC开发环境,如何部署ChatGLM2-6B大模型。
目录
相关文章
|
4月前
|
编解码 Linux 内存技术
LosslessCut倍速 LosslessCut github免费中文版,免费视频剪辑有哪些
LosslessCut 是一款免费开源的无损音视频剪切工具,支持 Win、Mac 和 Linux 平台。它无需重新编码即可快速裁剪音视频并保持高质量。软件支持多种格式,包括 MP4、MOV、FLAC 等,具备无损剪切、轨道编辑、元数据修改等功能,还提供中文界面切换及丰富快捷键操作,适合高效处理多媒体文件。
238 0
|
11月前
|
存储 人工智能 调度
阿里云吴结生:高性能计算持续创新,响应数据+AI时代的多元化负载需求
在数字化转型的大潮中,每家公司都在积极探索如何利用数据驱动业务增长,而AI技术的快速发展更是加速了这一进程。
|
11月前
|
安全 数据处理 Swift
深入探索iOS开发中的Swift语言特性
本文旨在为开发者提供对Swift语言在iOS平台开发的深度理解,涵盖从基础语法到高级特性的全面分析。通过具体案例和代码示例,揭示Swift如何简化编程过程、提高代码效率,并促进iOS应用的创新。文章不仅适合初学者作为入门指南,也适合有经验的开发者深化对Swift语言的认识。
246 9
|
存储 缓存 负载均衡
软件体系结构 - 数据分片(2)一致性哈希分片
【4月更文挑战第20天】软件体系结构 - 数据分片(2)一致性哈希分片
423 21
|
设计模式 前端开发 安全
理解最常用的MVC分层模型及其变种
【6月更文挑战第24天】 本文介绍架构模式如MVC、MVVM和MVP是解决软件结构问题的通用方案。。每种模式有其优缺点,适用场景不同。
757 0
理解最常用的MVC分层模型及其变种
|
Java 图形学 开发者
U3D小游戏开发秘籍:实战代码优化与性能提升技巧
【7月更文第13天】Unity 3D(U3D)以其强大的跨平台能力,成为小游戏开发者的宠儿。然而,在追求创意与乐趣的同时,如何确保项目高效运行,避免性能瓶颈,是每个开发者必须面对的课题。本文深入浅出,结合实战代码示例,揭示提升U3D小游戏性能与优化项目的艺术。
236 0
|
关系型数据库 Shell Linux
在Linux Shell中,`pgrep` 和 `pkill` 命令
在Linux Shell中,`pgrep` 和 `pkill` 命令
376 2
|
小程序 前端开发 定位技术
【微信小程序】-- 常用视图容器类组件介绍 -- view、scroll-view和swiper(六)
【微信小程序】-- 常用视图容器类组件介绍 -- view、scroll-view和swiper(六)
|
JSON JavaScript 前端开发
没有json数据,自己造!mockjs的使用-模拟数据其实超级简单
没有json数据,自己造!mockjs的使用-模拟数据其实超级简单
378 0
|
存储 人工智能 自然语言处理
ResearchRabbit.ai: 学术论文摘要研究工具
ResearchRabbit.ai: 学术论文摘要研究工具
642 0
ResearchRabbit.ai: 学术论文摘要研究工具