采用ggplot2繪制誤差線需要對(duì)數(shù)據(jù)轉(zhuǎn)換求得mean和sd(或se等)悔叽,可以通過(guò)Rmisc包summarySE函數(shù)、dplyr包group_by與summarise兩個(gè)函數(shù)等實(shí)現(xiàn)爵嗅,添加p-value(或顯著性標(biāo)記)可采用ggpubr包娇澎,然而添加p-value無(wú)需數(shù)據(jù)轉(zhuǎn)換。這樣睹晒,ggplot2同時(shí)繪制誤差線與p-value則需要采用多數(shù)據(jù)框趟庄,太過(guò)復(fù)雜。下面提供一個(gè)簡(jiǎn)單的一步到位法伪很。
#先加載包
library(ggplot2); library(ggpubr)
#加載數(shù)據(jù)集ToothGrowth
data("ToothGrowth")
tg <- ToothGrowth
tg$dose = as.factor (tg$dose)
head(tg)
p<- ggplot(tg, aes(x = dose, y = len, fill = supp)) +
geom_bar(stat = "summary", fun = mean, color = "black", position = position_dodge()) +
stat_summary(fun.data = 'mean_sd', geom = "errorbar", colour = "black",
width = 0.25,position = position_dodge( .9))
執(zhí)行stat_summary繪制誤差線戚啥,亦可用mean_se等
添加p-value
#方差齊性檢驗(yàn),利用car下的Levene檢驗(yàn)
library(car); library(purrr)
tg %>% split(.$dose) %>% map(~leveneTest(len ~ supp, data = .x, center = mean))
#不同dose下是掰,Levene檢驗(yàn)p值分別為0.052虑鼎、0.149、0.129键痛,表明各組總體方差相同(var.equal = TRUE)炫彩。
p + stat_compare_means(method = "t.test", method.args = list(var.equal = TRUE))
添加顯著性標(biāo)記
p + stat_compare_means(aes(label =..p.signif..), method = "t.test", method.args = list(var.equal = TRUE))