介绍

ggpubr是我经常会用到的R包,它傻瓜式的画图方式对很多初次接触R绘图的人来讲是很友好的。该包有个stat_compare_means函数可以做组间假设检验分析。更多知识分享请到 [https://zouhua.top/](https://zouhua.top/**)。

安装

安装R包可参考如何安装R包

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

密度图density

  1. ggdensity(plotdata,
  2. x = "weight",
  3. add = "mean",
  4. rug = TRUE, # x轴显示分布密度
  5. color = "sex",
  6. fill = "sex",
  7. palette = c("#00AFBB", "#E7B800"))

R包:ggpubr傻瓜式绘图包 - 图1

柱状图histogram

  1. gghistogram(plotdata,
  2. x = "weight",
  3. bins = 30,
  4. add = "mean",
  5. rug = TRUE,
  6. color = "sex",
  7. fill = "sex",
  8. palette = c("#00AFBB", "#E7B800"))

R包:ggpubr傻瓜式绘图包 - 图2

箱线图boxplot

  1. df <- ToothGrowth
  2. head(df)
  3. my_comparisons <- list( c("0.5", "1"), c("1", "2"), c("0.5", "2") )
  4. ggboxplot(df,
  5. x = "dose",
  6. y = "len",
  7. color = "dose",
  8. palette =c("#00AFBB", "#E7B800", "#FC4E07"),
  9. add = "jitter",
  10. shape = "dose")+
  11. stat_compare_means(comparisons = my_comparisons)+ # Add pairwise comparisons p-value
  12. stat_compare_means(label.y = 50)

R包:ggpubr傻瓜式绘图包 - 图3

小提琴图violin

  1. ggviolin(df,
  2. x = "dose",
  3. y = "len",
  4. fill = "dose",
  5. palette = c("#00AFBB", "#E7B800", "#FC4E07"),
  6. add = "boxplot",
  7. add.params = list(fill = "white"))+
  8. stat_compare_means(comparisons = my_comparisons, label = "p.signif")+ # Add significance levels
  9. stat_compare_means(label.y = 50)

R包:ggpubr傻瓜式绘图包 - 图4

点图dotplot

  1. ggdotplot(ToothGrowth,
  2. x = "dose",
  3. y = "len",
  4. color = "dose",
  5. palette = "jco",
  6. binwidth = 1)

R包:ggpubr傻瓜式绘图包 - 图5

有序条形图 ordered bar plots

  1. data("mtcars")
  2. dfm <- mtcars
  3. dfm$cyl <- as.factor(dfm$cyl)
  4. dfm$name <- rownames(dfm)
  5. head(dfm[, c("name", "wt", "mpg", "cyl")])
  6. ggbarplot(dfm,
  7. x = "name", y = "mpg",
  8. fill = "cyl", # change fill color by cyl
  9. color = "white", # Set bar border colors to white
  10. palette = "jco", # jco journal color palett. see ?ggpar
  11. sort.val = "asc", # Sort the value in dscending order
  12. sort.by.groups = TRUE, # Sort inside each group
  13. x.text.angle = 90) # Rotate vertically x axis texts

R包:ggpubr傻瓜式绘图包 - 图6

偏差图Deviation graphs

  1. dfm$mpg_z <- (dfm$mpg -mean(dfm$mpg))/sd(dfm$mpg)
  2. dfm$mpg_grp <- factor(ifelse(dfm$mpg_z < 0, "low", "high"),
  3. levels = c("low", "high"))
  4. # Inspect the data
  5. head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")])
  6. ggbarplot(dfm, x = "name", y = "mpg_z",
  7. fill = "mpg_grp", # change fill color by mpg_level
  8. color = "white", # Set bar border colors to white
  9. palette = "jco", # jco journal color palett. see ?ggpar
  10. sort.val = "asc", # Sort the value in ascending order
  11. sort.by.groups = FALSE, # Don't sort inside each group
  12. x.text.angle = 90, # Rotate vertically x axis texts
  13. ylab = "MPG z-score",
  14. rotate = FALSE,
  15. xlab = FALSE,
  16. legend.title = "MPG Group")

R包:ggpubr傻瓜式绘图包 - 图7

棒棒糖图 lollipop chart

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

R包:ggpubr傻瓜式绘图包 - 图8

偏差图Deviation graph

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

R包:ggpubr傻瓜式绘图包 - 图9

散点图scatterplot

  1. df <- datasets::iris
  2. head(df)
  3. ggscatter(df,
  4. x = 'Sepal.Width',
  5. y = 'Sepal.Length',
  6. palette = 'jco',
  7. shape = 'Species',
  8. add = 'reg.line',
  9. color = 'Species',
  10. conf.int = TRUE)

R包:ggpubr傻瓜式绘图包 - 图10

  • 添加回归线的系数
  1. ggscatter(df,
  2. x = 'Sepal.Width',
  3. y = 'Sepal.Length',
  4. palette = 'jco',
  5. shape = 'Species',
  6. add = 'reg.line',
  7. color = 'Species',
  8. conf.int = TRUE)+
  9. stat_cor(aes(color=Species),method = "pearson", label.x = 3)

R包:ggpubr傻瓜式绘图包 - 图11

  • 添加聚类椭圆 concentration ellipses
  1. data("mtcars")
  2. dfm <- mtcars
  3. dfm$cyl <- as.factor(dfm$cyl)
  4. dfm$name <- rownames(dfm)
  5. p1 <- ggscatter(dfm,
  6. x = "wt",
  7. y = "mpg",
  8. color = "cyl",
  9. palette = "jco",
  10. shape = "cyl",
  11. ellipse = TRUE)
  12. p2 <- ggscatter(dfm,
  13. x = "wt",
  14. y = "mpg",
  15. color = "cyl",
  16. palette = "jco",
  17. shape = "cyl",
  18. ellipse = TRUE,
  19. ellipse.type = "convex")
  20. cowplot::plot_grid(p1, p2, align = "hv", nrow = 1)

R包:ggpubr傻瓜式绘图包 - 图12

  • 添加mean和stars
  1. ggscatter(dfm, x = "wt", y = "mpg",
  2. color = "cyl", palette = "jco",
  3. shape = "cyl",
  4. ellipse = TRUE,
  5. mean.point = TRUE,
  6. star.plot = TRUE)

R包:ggpubr傻瓜式绘图包 - 图13

  • 显示点标签
  1. dfm$name <- rownames(dfm)
  2. p3 <- ggscatter(dfm,
  3. x = "wt",
  4. y = "mpg",
  5. color = "cyl",
  6. palette = "jco",
  7. label = "name",
  8. repel = TRUE)
  9. p4 <- ggscatter(dfm,
  10. x = "wt",
  11. y = "mpg",
  12. color = "cyl",
  13. palette = "jco",
  14. label = "name",
  15. repel = TRUE,
  16. label.select = c("Toyota Corolla", "Merc 280", "Duster 360"))
  17. cowplot::plot_grid(p3, p4, align = "hv", nrow = 1)

R包:ggpubr傻瓜式绘图包 - 图14

气泡图bubble plot

  1. ggscatter(dfm,
  2. x = "wt",
  3. y = "mpg",
  4. color = "cyl",
  5. palette = "jco",
  6. size = "qsec",
  7. alpha = 0.5)+
  8. scale_size(range = c(0.5, 15)) # Adjust the range of points size

R包:ggpubr傻瓜式绘图包 - 图15

连线图 lineplot

  1. p1 <- ggbarplot(ToothGrowth,
  2. x = "dose",
  3. y = "len",
  4. add = "mean_se",
  5. color = "supp",
  6. palette = "jco",
  7. position = position_dodge(0.8))+
  8. stat_compare_means(aes(group = supp), label = "p.signif", label.y = 29)
  9. p2 <- ggline(ToothGrowth,
  10. x = "dose",
  11. y = "len",
  12. add = "mean_se",
  13. color = "supp",
  14. palette = "jco")+
  15. stat_compare_means(aes(group = supp), label = "p.signif",
  16. label.y = c(16, 25, 29))
  17. cowplot::plot_grid(p1, p2, ncol = 2, align = "hv")

R包:ggpubr傻瓜式绘图包 - 图16

添加边沿图 marginal plots

  1. library(ggExtra)
  2. p <- ggscatter(iris,
  3. x = "Sepal.Length",
  4. y = "Sepal.Width",
  5. color = "Species",
  6. palette = "jco",
  7. size = 3,
  8. alpha = 0.6)
  9. ggMarginal(p, type = "boxplot")

R包:ggpubr傻瓜式绘图包 - 图17

  • 第二种添加方式: 分别画出三个图,然后进行组合
  1. sp <- ggscatter(iris,
  2. x = "Sepal.Length",
  3. y = "Sepal.Width",
  4. color = "Species",
  5. palette = "jco",
  6. size = 3,
  7. alpha = 0.6,
  8. ggtheme = theme_bw())
  9. xplot <- ggboxplot(iris,
  10. x = "Species",
  11. y = "Sepal.Length",
  12. color = "Species",
  13. fill = "Species",
  14. palette = "jco",
  15. alpha = 0.5,
  16. ggtheme = theme_bw())+ rotate()
  17. yplot <- ggboxplot(iris,
  18. x = "Species",
  19. y = "Sepal.Width",
  20. color = "Species",
  21. fill = "Species",
  22. palette = "jco",
  23. alpha = 0.5,
  24. ggtheme = theme_bw())
  25. sp <- sp + rremove("legend")
  26. yplot <- yplot + clean_theme() + rremove("legend")
  27. xplot <- xplot + clean_theme() + rremove("legend")
  28. cowplot::plot_grid(xplot, NULL, sp, yplot, ncol = 2, align = "hv",
  29. rel_widths = c(2, 1), rel_heights = c(1, 2))

R包:ggpubr傻瓜式绘图包 - 图18

  • 上图主图和边沿图之间的space太大,第三种方法能克服这个缺点
  1. library(cowplot)
  2. # Main plot
  3. pmain <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))+
  4. geom_point()+
  5. ggpubr::color_palette("jco")
  6. # Marginal densities along x axis
  7. xdens <- axis_canvas(pmain, axis = "x")+
  8. geom_density(data = iris, aes(x = Sepal.Length, fill = Species),
  9. alpha = 0.7, size = 0.2)+
  10. ggpubr::fill_palette("jco")
  11. # Marginal densities along y axis
  12. # Need to set coord_flip = TRUE, if you plan to use coord_flip()
  13. ydens <- axis_canvas(pmain, axis = "y", coord_flip = TRUE)+
  14. geom_boxplot(data = iris, aes(x = Sepal.Width, fill = Species),
  15. alpha = 0.7, size = 0.2)+
  16. coord_flip()+
  17. ggpubr::fill_palette("jco")
  18. p1 <- insert_xaxis_grob(pmain, xdens, grid::unit(.2, "null"), position = "top")
  19. p2 <- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right")
  20. ggdraw(p2)

R包:ggpubr傻瓜式绘图包 - 图19

  • 第四种方法,通过grob设置
  1. # Scatter plot colored by groups ("Species")
  2. #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  3. sp <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
  4. color = "Species", palette = "jco",
  5. size = 3, alpha = 0.6)
  6. # Create box plots of x/y variables
  7. #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  8. # Box plot of the x variable
  9. xbp <- ggboxplot(iris$Sepal.Length, width = 0.3, fill = "lightgray") +
  10. rotate() +
  11. theme_transparent()
  12. # Box plot of the y variable
  13. ybp <- ggboxplot(iris$Sepal.Width, width = 0.3, fill = "lightgray") +
  14. theme_transparent()
  15. # Create the external graphical objects
  16. # called a "grop" in Grid terminology
  17. xbp_grob <- ggplotGrob(xbp)
  18. ybp_grob <- ggplotGrob(ybp)
  19. # Place box plots inside the scatter plot
  20. #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  21. xmin <- min(iris$Sepal.Length); xmax <- max(iris$Sepal.Length)
  22. ymin <- min(iris$Sepal.Width); ymax <- max(iris$Sepal.Width)
  23. yoffset <- (1/15)*ymax; xoffset <- (1/15)*xmax
  24. # Insert xbp_grob inside the scatter plot
  25. sp + annotation_custom(grob = xbp_grob, xmin = xmin, xmax = xmax,
  26. ymin = ymin-yoffset, ymax = ymin+yoffset) +
  27. # Insert ybp_grob inside the scatter plot
  28. annotation_custom(grob = ybp_grob,
  29. xmin = xmin-xoffset, xmax = xmin+xoffset,
  30. ymin = ymin, ymax = ymax)

R包:ggpubr傻瓜式绘图包 - 图20

二维密度图 2d density

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

R包:ggpubr傻瓜式绘图包 - 图21

混合图

混合表、字体和图

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

R包:ggpubr傻瓜式绘图包 - 图22

  • 注释table在图上
  1. density.p <- ggdensity(iris, x = "Sepal.Length",
  2. fill = "Species", palette = "jco")
  3. stable <- desc_statby(iris, measure.var = "Sepal.Length",
  4. grps = "Species")
  5. stable <- stable[, c("Species", "length", "mean", "sd")]
  6. stable.p <- ggtexttable(stable, rows = NULL,
  7. theme = ttheme("mOrange"))
  8. density.p + annotation_custom(ggplotGrob(stable.p),
  9. xmin = 5.5, ymin = 0.7,
  10. xmax = 8)

R包:ggpubr傻瓜式绘图包 - 图23

systemic information

  1. sessionInfo()
  1. R version 3.6.1 (2019-07-05)
  2. Platform: x86_64-w64-mingw32/x64 (64-bit)
  3. Running under: Windows 10 x64 (build 19042)
  4. Matrix products: default
  5. locale:
  6. [1] LC_COLLATE=Chinese (Simplified)_China.936 LC_CTYPE=Chinese (Simplified)_China.936
  7. [3] LC_MONETARY=Chinese (Simplified)_China.936 LC_NUMERIC=C
  8. [5] LC_TIME=Chinese (Simplified)_China.936
  9. attached base packages:
  10. [1] stats graphics grDevices utils datasets methods base
  11. other attached packages:
  12. [1] ggpubr_0.4.0 ggplot2_3.3.2
  13. loaded via a namespace (and not attached):
  14. [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
  15. [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
  16. [13] rlang_0.4.8 openxlsx_4.2.3 ggsci_2.9 rstudioapi_0.10 curl_4.3 haven_2.3.1
  17. [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
  18. [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
  19. [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
  20. [37] car_3.0-10 magrittr_1.5 scales_1.1.0 backports_1.1.10 ellipsis_0.3.1 abind_1.4-5
  21. [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
  22. [49] crayon_1.3.4

Reference

  1. ggpubr: Publication Ready Plots

参考文章如引起任何侵权问题,可以与我联系,谢谢。