copy from: https://www.jianshu.com/p/3862faf22c14
# 清空环境变量
rm(list=ls())
# 安装、载入包
install.packages("ggpubr")
library(ggpubr)
install.packages("ggsci")
library(ggsci)
# 加载数据集,并查看
data("ToothGrowth")
str(ToothGrowth)
head(ToothGrowth)
ggboxplot函数
ggboxplot为ggpubr包的函数。
ggboxplot(data, x, y, color = "black", bxp.errorbar = FALSE)
data | a data frame |
---|---|
x | character string containing the name of x variable |
y | character vector containing one or more variables to plot |
color | outline color |
palette | the color palette to be used for coloring or filling by groups. Allowed values include "grey" for grey color palettes; brewer palettes e.g. "RdBu", "Blues", ...; or custom color palette e.g. c("blue", "red"); and scientific journal palettes from ggsci R package, e.g.: "npg", "aaas", "lancet", "jco", "ucscgb", "uchicago", "simpsons" and "rickandmorty". |
bxp.errorbar | logical value. If TRUE, shows error bars of box plots. |
#从lancet调色板提取9个颜色
pal = pal_lancet("lanonc")(9)
#选取前3个颜色
colors = pal_lancet("lanonc")(9)[1:3]
my_comparisons = list(c("0.5","1"),c("1","2"), c("0.5","2"))
p = ggboxplot( ToothGrowth , x = "dose", y = "len", color = "dose" , palette =colors, bxp.errorbar = T) +
stat_compare_means(comparisons =my_comparisons) +stat_compare_means(method = "anova" , label.x = 1.7, label.y = 45)
p
p + stat_boxplot(geom ="errorbar", color = colors, width =0.4, size =1) + geom_boxplot(aes(color = dose))
p
stat_compare_means
- ggpubr包的函数
- Add mean comparison p-values to a ggplot, such as box blots, dot plots and stripcharts.
- stat_compare_means(method = NULL, comparisons = NULL, label.x = NULL, label.y = NULL)
method | a character string indicating which method to be used for comparing means. |
---|---|
comparisons | A list of length-2 vectors. The entries in the vector are either the names of 2 values on the x-axis or the 2 integers that correspond to the index of the groups of interest, to be compared. |
label.x,label.y | numeric Coordinates (in data units) to be used for absolute positioning of the label. If too short they will be recycled. |
stat_boxplot
- ggplot2包函数,A box and whiskers plot (in the style of Tukey)
- The boxplot compactly displays the distribution of a continuous variable. It visualises five summary statistics (the median, two hinges and two whiskers), and all "outlying" points individually.
- stat_boxplot(geom ="errorbar", color = colors, width =0.4, size =1) + geom_boxplot(aes(color = dose))
结果展示: