R语言学习笔记--ggplot2一步到位绘制误差线及p-valu
2018-11-30 本文已影响203人
逍遥尐生
采用ggplot2绘制误差线需要对数据转换求得mean和sd(或se等),可以通过Rmisc包summarySE函数、dplyr包group_by与summarise两个函数等实现,添加p-value(或显著性标记)可采用ggpubr包,然而添加p-value无需数据转换。这样,ggplot2同时绘制误差线与p-value则需要采用多数据框,太过复杂。下面提供一个简单的一步到位法。
#先加载包
library(ggplot2); library(ggpubr)
#加载数据集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.y = mean, color = "black", position = position_dodge()) +
stat_summary(fun.data = 'mean_sd', geom = "errorbar", colour = "black",
width = 0.25,position = position_dodge( .9)
执行stat_summary绘制误差线,亦可用mean_se等
添加p-value
p + stat_compare_means(method = "t.test")

添加显著性标记
p + stat_compare_means(aes(label =..p.signif..), method = "t.test")
