其他
R优雅的进行多因素方差分析
欢迎关注R语言数据分析指南
❝本节来介绍如何使用R做单因素与多因素方差分析,绘制并排堆砌条形图并添加显著性字母标记,下面来看具体例子
❞
安装并加载R包
library(tidyverse)
library(multcompView)
library(stats)
library(ggsci)
加载数据
data2 <- ToothGrowth %>% mutate(dose=as.factor(dose))
计算方差
anova <- aov(len ~ supp*dose, data = data2)
summary(anova)
多重均值比较
tukey <- TukeyHSD(anova)
group_lettering <- multcompLetters4(anova, tukey) # 提取字母
❝计算均值,标准差并添加字母
❞
mean_data2 <- data2 %>%
group_by(supp, dose) %>%
summarise(len_mean=mean(len), sd = sd(len)) %>%
arrange(desc(len_mean))
mean_data2$group_lettering <- group_lettering$group_lettering..supp.dose..Letters
# A tibble: 6 x 5
# Groups: supp [2]
supp dose len_mean sd group_lettering
<fct> <fct> <dbl> <dbl> <chr>
1 VC 2 26.1 4.80 a
2 OJ 2 26.1 2.66 a
3 OJ 1 22.7 3.91 a
4 VC 1 16.8 2.52 b
5 OJ 0.5 13.2 4.46 b
6 VC 0.5 7.98 2.75 c
绘制基础条形图
ggplot(mean_data2, aes(x = dose, y = len_mean,group=supp)) +
geom_bar(position=position_dodge(0.9),stat = "identity", aes(fill = supp),
show.legend = TRUE)
添加误差线
ggplot(mean_data2, aes(x = dose, y = len_mean,group=supp)) +
geom_bar(position=position_dodge(0.9),stat = "identity",
aes(fill = supp),show.legend = TRUE) +
geom_errorbar(aes(ymin = len_mean-sd, ymax=len_mean+sd),width = 0.1,
position=position_dodge(0.9))
添加字母
ggplot(mean_data2, aes(x = dose, y = len_mean,group=supp))+
geom_bar(position=position_dodge(0.9),stat = "identity",
aes(fill = supp), show.legend = TRUE) +
geom_errorbar(aes(ymin = len_mean-sd, ymax=len_mean+sd),
width = 0.1, position=position_dodge(0.9)) +
geom_text(aes(label = group_lettering, y = len_mean + sd),
vjust=-0.4,position=position_dodge(0.9))
修改主题
ggplot(mean_data2, aes(x = dose, y = len_mean,group=supp))+
geom_bar(position=position_dodge(0.9),stat = "identity",
aes(fill = supp), show.legend = TRUE) +
geom_errorbar(aes(ymin = len_mean-sd, ymax=len_mean+sd),
width = 0.1, position=position_dodge(0.9)) +
geom_text(aes(label = group_lettering, y = len_mean + sd),
vjust=-0.4, position=position_dodge(0.9)) +
scale_y_continuous(expand = expansion(0),limits = c(0,35),
breaks = seq(0,35,5))+
labs(x=NULL,y=NULL)+
theme(
plot.margin = unit(c(0.2,0.2,0.2,0.2), "cm"),
panel.background = element_blank(),
axis.line = element_line(color = "black"),
axis.title = element_text(size = 10, color = "black",face = "bold"),
axis.text = element_text(size = 10,color = "black"),
axis.text.x = element_text(margin=margin(t =3)),
axis.text.y = element_text(size = 10),
axis.title.y = element_text(margin = margin(r = 10)),
axis.ticks.x = element_blank())+
scale_fill_jco()
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐