将 Pearson 卡方检验的 p 值添加到分面 ggplots

add p-values of Pearson's chi-squared test to facet ggplots

我比较了三个不同组的分类数据。

我想知道是否可以轻松地将卡方检验的 p 值添加到分面 ggplots(因为我正在分析一个大数据集)。我刚刚读到,在比较均值 https://www.r-bloggers.com/add-p-values-and-significance-levels-to-ggplots/ 时,有一种绝妙的方法可以做到这一点。但是,我找不到其他测试的解决方案(比如我的 chisq.test)。

d.test <- data.frame(
  results = sample(c("A","B","C"), 30, replace =TRUE),
  test = sample(c("test1", "test2","test3"), 30, replace = TRUE)
)

chisq.test(d.test$results,d.test$test)

ggplot(d.test, aes(results) ) +
  geom_bar() + facet_grid(test ~ .)

非常感谢您的帮助! ;D

将您的 p 值存储在变量中

pval <- chisq.test(d.test$results,d.test$test)$p.value

使用annotate手动绘制文本

ggplot(d.test, aes(results) ) +
  geom_bar() + facet_grid(test ~ .) +
  annotate("text", x=1, y=5, label=pval)

xy改变其定位

ggplot(d.test, aes(results) ) +
  geom_bar() + facet_grid(test ~ .) +
  annotate("text", x=2, y=3, label=pval)    

更改 signif

显示的有效数字
ggplot(d.test, aes(results) ) +
  geom_bar() + facet_grid(test ~ .) +
  annotate("text", x=1, y=5, label=signif(pval,4))

添加一个 'label' p-value:

ggplot(d.test, aes(results) ) +
  geom_bar() + facet_grid(test ~ .) +
  annotate("text", x=1, y=5, label=paste0("p-value: ", signif(pval,4)))

broom 有方法可以为大多数统计测试输出创建整洁的数据帧。然后您可以将该输出用作 geom_text.

中的 data = 参数

生成数据

library(broom)
library(dplyr)
library(ggplot2)

fakedata <- 
  data.frame(groups = sample(c("pop1", "pop2", "pop3", "pop4"), 120, replace = T),
             results = sample(c("A","B","C"), 120, replace = TRUE),
             test = sample(c("test1", "test2","test3"), 120, replace = TRUE))

进行并整理测试

fakedata.test <-
  fakedata %>% 
    group_by(groups) %>% 
    do(fit = chisq.test(.$results, .$test)) %>% 
    tidy(fit)
# A tibble: 4 x 5
# Groups:   groups [4]
  groups statistic    p.value parameter                     method
  <fctr>     <dbl>      <dbl>     <int>                     <fctr>
1   pop1  3.714286 0.44605156         4 Pearson's Chi-squared test
2   pop2  2.321429 0.67687042         4 Pearson's Chi-squared test
3   pop3  2.294897 0.68169829         4 Pearson's Chi-squared test
4   pop4 10.949116 0.02714188         4 Pearson's Chi-squared test

可视化

fakedata %>% 
  ggplot(aes(results, test)) + 
  geom_jitter(width = 0.2, height = 0.2, shape = 1, size = 2) +
  geom_text(data = fakedata.test,
            aes(3, 3.5, 
                label = paste0("χ²(", parameter, ")=", round(statistic, 2), "; p=", round(p.value, 2))),
            hjust = 1) +
  facet_wrap(~groups)