Programming/R
[R] ggplot에 dodge이용시 p-value값 넣는 방법 3가지
김해김씨99대손
2023. 2. 17. 16:46
dodge옵션에서 통계적 계산을 하려면 생각보다 손이 많이 간다. 물론 rstatix가 많은 도움을 주긴 하지만, 이를 위해 데이터 준비 하는 과정도 만만치는 않다. 이와 비슷한 방법을 여러가지 알아보자.
library(rstatix)
library(ggplot2)
library(ggpurb)
데이터 준비
df <- ToothGrowth
df$dose <- as.factor(df$dose)
head(df, 3)
방법1 : ggpurb 이용, position_dodge 이용
stat.test <- df %>%
group_by(dose) %>%
t_test(len ~ supp) %>%
adjust_pvalue(method = "bonferroni") %>%
add_significance("p.adj")
# x축, y축 값 추가하기
stat.test <- stat.test %>%
add_xy_position(fun = "mean_sd", x = "dose", dodge = 0.8)
# bar plot 그리기
bp <- ggbarplot(
df, x = "dose", y = "len", add = "mean_sd",
color= "supp", palette = c("#00AFBB", "#E7B800"),
position = position_dodge(0.8)
)
# p값 추가하기
bp + stat_pvalue_manual(
stat.test, label = "p.adj.signif", tip.length = 0.01
)
방법2 : ggplot2 이용, facet 이용
ggplot(df, aes(x = supp, y = len)) +
geom_bar(stat="identity") +
facet_wrap(~dose) +
stat_compare_means(
aes(label = paste0("p = ", after_stat(p.format))),
label.y = 270
)
방법3 : ggplot2이용, position_dodge 이용
stat.test <- df %>%
group_by(dose) %>%
t_test(len ~ supp) %>%
adjust_pvalue(method = "bonferroni") %>%
add_significance("p.adj") %>%
add_xy_position(fun = "mean_sd", x = "dose", dodge = 0.8)
stat.test
ggplot(df, aes(x = dose, y = len)) +
geom_bar(aes(fill = supp), stat="identity", position=position_dodge(0.9)) +
stat_pvalue_manual(
stat.test, label = "p.adj.signif", tip.length = 0.01
)
출처
https://www.datanovia.com/en/blog/how-to-add-p-values-onto-a-grouped-ggplot-using-the-ggpubr-r-package/
https://github.com/kassambara/ggpubr/issues/65
반응형