ggpubr|让数据可视化更加优雅

ggpubr_cover.jpg

ggpubr的基础用法指南

ggpubr_github

ggpubr是由Alboukadel Kassambara创建的,基于ggplot2的可视化包。主要用于绘制符合出版要求的图形。

本文代码领取:后台回复 ggpubr

安装与加载

  • CRAN安装:
install.packages("ggpubr")
  • 或者从GitHub上安装最新版本:
# Install
if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/ggpubr")
  • 加载包
library(ggplot2)
library(ggpubr)

分布图

# 构建数据集
set.seed(1234)
#set.seed()设定生成随机数的种子,种子是为了让结果具有重复性,重现结果。如果不设定种子,生成的随机数无法重现。
wdata = data.frame(
   sex = factor(rep(c("F", "M"), each=200)),
   weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata, 4)

set.seed(1234)

set.seed()设定生成随机数的种子,种子是为了让结果具有重复性,重现结果。如果不设定种子,生成的随机数无法重现。

wdata = data.frame(
sex = factor(rep(c("F", "M"), each=200)),
weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata, 4)


```R
> head(wdata, 4)
  sex   weight
1   F 53.79293
2   F 55.27743
3   F 56.08444
4   F 52.65430

密度分布图

ggdensityggdensity(wdata, x = "weight",
   add = "mean", rug = TRUE,
   color = "sex", fill = "sex",
   palette = c("#00AFBB", "#E7B800"))
#参数详解
Usage
ggdensity(
  data,
  x,
  y = "..density..",
  combine = FALSE,#对于多类型数据是否分面
  merge = FALSE,#对于多类型数据是否合并
  color = "black",#线条颜色
  fill = NA,#线条填充色
  palette = NULL,#自定义颜色画板
  size = NULL,#点、线大小
  linetype = "solid",#线条类型
  alpha = 0.5,#透明度
  title = NULL,#设置标题
  xlab = NULL,#设置x轴标题
  ylab = NULL,#设置y轴标题
  facet.by = NULL,#设置分组分面
  panel.labs = NULL,#设置分面各组的标题
  short.panel.labs = TRUE,
  add = c("none", "mean", "median"),#添加均值或中位数线
  add.params = list(linetype = "dashed"),#添加其他参数
  rug = FALSE,#是否添加边际线
  label = NULL,#设置列标签
  font.label = list(size = 11, color = "black"), #设置标签字体
  label.select = NULL,
  repel = FALSE,#是否避字体免重叠 
  label.rectangle = FALSE,#是否给标签添加方框
  ggtheme = theme_pubr(),#设置画图主题 
  ...
)

直方图

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

箱线图和小提琴图

#导入内置数据
data("ToothGrowth")
df <- ToothGrowth
head(df, 4)
> head(df, 4)
   len supp dose
1  4.2   VC  0.5
2 11.5   VC  0.5
3  7.3   VC  0.5
4  5.8   VC  0.5

箱线图

p <- ggboxplot(df,
               x = "dose", 
               y = "len",
               color = "dose", 
               palette =c("#00AFBB", "#E7B800", "#FC4E07"),
               add = "jitter",#添加散点 
               shape = "dose"#点的形状)
p
 # 添加P值
 # 建立需要比较的分组
my_comparisons <- list( c("0.5", "1"), c("1", "2"), c("0.5", "2") )
p + stat_compare_means(comparisons = my_comparisons)+ # 添加两两比较的p-value
  stat_compare_means(label.y = 50)                   # 添加多组间比较p-value
# 参数详解
stat_compare_means(
  mapping = NULL,
  data = NULL,
  method = NULL,#检验方法见下表
  paired = FALSE,#是否配对
  method.args = list(),#用于检验的附加参数,如method.args = list(alternative = "greater")
  ref.group = NULL,#指定对照组
  comparisons = NULL,#包含比较分组的列表
  hide.ns = FALSE,#是否隐藏无差异的标志ns
  label.sep = ", ",#分隔术语的字符串。默认为“,”,以分离相关系数和p值
  label = NULL,#标签
  label.x.npc = "left",#标签的x轴位置
  label.y.npc = "top",#标签的y轴位置
  #数字0~1,或者字符('right', 'left', 'center', 'centre', 'middle')
  label.x = NULL,
  label.y = NULL,#指定一个数值,表示显示标签的绝对坐标位置
  vjust = 0,#向上或向下移动文本
  tip.length = 0.03,
  bracket.size = 0.3,
  step.increase = 0,
  symnum.args = list(),#默认symnum.args <- list(cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 1), symbols = c("****", "***", "**", "*", "ns")).可以自己修改
  geom = "text",
  position = "identity",
  na.rm = FALSE,#如果为FALSE(默认值),则通过警告删除缺失的值。如果为真,则静默删除缺失的值。
  show.legend = NA,#是否包含图例
  inherit.aes = TRUE,
  ...
)

常用的统计学方法

方法 R实现函数 描述
T-test t.test() 比较两组(参数检验)
Wilcoxon test wilcox.test() 比较两组(非参数检验)
ANOVA aov()或anova() 比较多组(参数检验)
Kruskal-Wallis kruskal.test() 比较多组(非参数检验)

小提琴图+箱线图

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")+ 
         stat_compare_means(label.y = 50)                                      

条图

#构建数据集
# 导入内置数据
data("mtcars")
dfm <- mtcars
# 将cyl变量转为因子
dfm$cyl <- as.factor(dfm$cyl)
# 添加name列
dfm$name <- rownames(dfm)
#检查数据
head(dfm[, c("name", "wt", "mpg", "cyl")])
> head(dfm[, c("name", "wt", "mpg", "cyl")])
                               name    wt  mpg cyl
Mazda RX4                 Mazda RX4 2.620 21.0   6
Mazda RX4 Wag         Mazda RX4 Wag 2.875 21.0   6
Datsun 710               Datsun 710 2.320 22.8   4
Hornet 4 Drive       Hornet 4 Drive 3.215 21.4   6
Hornet Sportabout Hornet Sportabout 3.440 18.7   8
Valiant                     Valiant 3.460 18.1   6

顺序条图

ggbarplot(dfm, x = "name", y = "mpg",
          fill = "cyl",               # 根据cyl分组填充颜色
          color = "white",            #设置条形边框颜色为白色
          palette = "jco",            # jco杂志配色
          sort.val = "desc",          # 降序
          sort.by.groups = FALSE,     # 不按组排序
          x.text.angle = 90           # 垂直旋转x轴文本角度
          )
ggbarplot(dfm, x = "name", y = "mpg",
          fill = "cyl",              
          color = "white",            
          palette = "jco",           
          sort.val = "asc",           # 升序
          sort.by.groups = TRUE,      # 先分组先排序
          x.text.angle = 90         
          )

偏差图

偏差图显示了定量值与参考值的偏差。

z分数(z-score),也叫标准分数(standard score)是一个数与平均数的差再除以标准差的过程。在统计学中,标准分数是一个观测或数据点的值高于被观测值或测量值的平均值的标准偏差的符号数。

#计算mpg数据的 z-score
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")) #根据z分数分组并添加为新列。很好用的代码可以记记
head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")])
> head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")])
                               name    wt  mpg      mpg_z mpg_grp cyl
Mazda RX4                 Mazda RX4 2.620 21.0  0.1508848    high   6
Mazda RX4 Wag         Mazda RX4 Wag 2.875 21.0  0.1508848    high   6
Datsun 710               Datsun 710 2.320 22.8  0.4495434    high   4
Hornet 4 Drive       Hornet 4 Drive 3.215 21.4  0.2172534    high   6
Hornet Sportabout Hornet Sportabout 3.440 18.7 -0.2307345     low   8
Valiant                     Valiant 3.460 18.1 -0.3302874     low   6
ggbarplot(dfm, x = "name", y = "mpg_z",
          fill = "mpg_grp",           
          color = "white",            
          palette = "jco",          
          sort.val = "asc",           
          sort.by.groups = FALSE,     
          x.text.angle = 90,          
          ylab = "MPG z-score",
          xlab = FALSE,
          legend.title = "MPG Group"
          )
ggbarplot(dfm, x = "name", y = "mpg_z",
          fill = "mpg_grp",           
          color = "white",            
          palette = "jco",            
          sort.val = "desc",          #降序
          sort.by.groups = FALSE,     
          x.text.angle = 90,          
          ylab = "MPG z-score",
          legend.title = "MPG Group",
          rotate = TRUE,              #纵向
          ggtheme = theme_minimal()
          )

点图

棒棒糖图

ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                                #颜色分组
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), #常规调色板
           sorting = "ascending",                        # 升序
           add = "segments",                             # 将y = 0的段添加到点
           ggtheme = theme_pubr()                        # 主题
           )
ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                                
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), 
           sorting = "descending",                       #降序
           add = "segments",                            
           rotate = TRUE,                                #纵向
           group = "cyl",                                #先分组
           dot.size = 6,                                 #点大小
           label = round(dfm$mpg),                       #点标签
           font.label = list(color = "white", size = 9,
                             vjust = 0.5),               #调整标签参数
           ggtheme = theme_pubr()                        
           )
ggdotchart(dfm, x = "name", y = "mpg_z",
           color = "cyl",                               
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), 
           sorting = "descending",                      
           add = "segments",                             
           add.params = list(color = "lightgray", size = 2), # 更改棒(线条)颜色和大小
           group = "cyl",                                
           dot.size = 6,                                
           label = round(dfm$mpg_z,1),                        
           font.label = list(color = "white", size = 9,
                             vjust = 0.5),               
           ggtheme = theme_pubr()                       
           )+
  geom_hline(yintercept = 0, linetype = 2, color = "lightgray") #绘制水平线

Cleveland点图

ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                               
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), 
           sorting = "descending",                       
           rotate = TRUE,                                
           dot.size = 2,                                 
           y.text.col = TRUE,                            
           ggtheme = theme_pubr()                        
           )+
  theme_cleveland()                                      #Cleveland主题
Cleveland

参考

https://rpkgs.datanovia.com/ggpubr/


往期内容:

ggsci | 让你的配色Nature化

单细胞转录组|Seurat 4.0 使用指南

你可能感兴趣的:(ggpubr|让数据可视化更加优雅)