用ggpubr包制图

简介: Hadley Wickham撰写的ggplot2[1]是好用的软件包,是可视化工具的必备包。但是,需要知道ggplot2一定的理论与原理,对新手来说,入门门槛还是比较高的。而ggpubr软件包提供了一些易于使用的功能,基于ggplot2编写,语法十分简单的的图标。对于一些刚了解R语言,而想用R做可发表的图表的人来说,这真的太好用了!下面对该文章ggpubr: Publication Ready Plots[2]进行讲解。

简介


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)

2{ZT)E2ME@7(WRZRY1HK4{T.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"))

{]V_6$~M1PMSKI14M3H9PMW.png

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

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

N}ZW5M9E[_03[%~PLKAX8VG.png


箱型图

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

{WU9@]UMKJ}CDI1_2VQ6UTY.png

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

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

X4YHHZL3N%0X(U]68]02979.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

image.gif

小提琴图

下图是小提琴图(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

WTX%JV`%SOQX]4X~%B)9OCY.png


条形图

数据集

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

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

RK%M1C6HAAR2I`J8I}[KU{H.png


有序的条形图

条形图(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
          )

image.gif

如果按照组内排序的话(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
          )

BWZQ1KXBU36Z66H`GH15[CV.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")])

image.gif

根据上面的数据,创建一个有序的箱型图,按升序对值排序(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"
          )

V8ONUYBYO5LRLLBPK%VLCSU.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()
          )

image.gif

散点图

棒糖图

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

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
           )

D$~Q92A(LK94FHD~QPCMXCQ.png

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
           )

image.gif

偏差图

还是使用上面的数据集,构建棒棒糖系列的偏差图。改变线段的颜色和大小: 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")

7}DN0IE$Z@EC~GDBE04__SO.png


克利夫兰散点图

在前面的基础上,只要加入以下代码即可得到克利夫兰散点图(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

8MN~[5[}V@D4KD9EN4$%7HA.png

相关实践学习
部署Stable Diffusion玩转AI绘画(GPU云服务器)
本实验通过在ECS上从零开始部署Stable Diffusion来进行AI绘画创作,开启AIGC盲盒。
目录
相关文章
|
6月前
|
人工智能
怎么用Midjourney制作表情包
怎么用Midjourney制作表情包
159 0
|
3月前
|
JSON JavaScript API
用Python编写小工具下载OSM路网数据
用Python编写小工具下载OSM路网数据
|
6月前
|
数据可视化 API 数据库
R包:disgenet2r|DisGeNET的懒癌福利,一行代码多种可视化
DisGeNET是一个综合性的数据库,包含大量关于人类基因和疾病关联的信息,常用于生物信息学和基因组学研究。disgenet2r是R语言工具,方便用户访问和分析DisGeNET数据。用户需注册DisGeNET账号并安装R包,通过disgenet2r包可查询、检索基因-疾病关联和变异-疾病关联数据。目前DisGeNET包含超过110万个基因-疾病关联和30万个变异-疾病关联。使用示例包括查询特定疾病相关基因和多疾病联合分析。
192 0
|
6月前
|
定位技术
R语言GD包地理探测器分析时报错、得不到结果等情况的解决方案
R语言GD包地理探测器分析时报错、得不到结果等情况的解决方案
169 1
|
编解码 监控 开发工具
DirectShow捕获+mencoder+ffmpeg+sox 打造小巧的音视频制作、加工软件
DirectShow捕获+mencoder+ffmpeg+sox 打造小巧的音视频制作、加工软件
93 0
DirectShow捕获+mencoder+ffmpeg+sox 打造小巧的音视频制作、加工软件
|
uml Python
将python源码自动生成UML图——扩张包Graphviz+Pyreverse
将python源码自动生成UML图——扩张包Graphviz+Pyreverse
611 0
|
数据可视化
使用 ggpubr 包制图
使用 ggpubr 包制图
141 0
|
定位技术
轻松get七普数据or制图教程
轻松get七普数据or制图教程
120 0