2

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

我想知道是否可以轻松地将卡方检验的 p 值添加到 facet 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

4

2 回答 2

5

将您的 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)

x用and改变它的位置y

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))

添加一个“标签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)))
于 2017-09-07T17:14:14.157 回答
4

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

生成数据

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)

在此处输入图像描述

于 2017-09-07T21:46:49.337 回答