具有p值的动画小提琴/箱形图,用于成对的Wilcoxon测试

时间:2018-11-20 17:33:32

标签: r ggplot2 dplyr gganimate ggpubr

我正在尝试为R中的配对wilcox测试添加p值。我正在使用以下代码。下面的代码创建两种饮食(治疗)的结局读数(二头肌)的小提琴(密度分布)。这些小提琴会随着时间1,时间2,时间3进行动画处理。图形的顶部显示p值。我希望这些p值成为配对值,例如

对于“ a”饮食,将2时的二头肌读数与1时相比较,并将3时的二头肌读数与1时相比较。

与饮食“ b”相同。因此,应该在时间2和时间3在小提琴的顶部分别打印两个p值。分别指示饮食“ a”和饮食“ b”的配对测试(时间2与时间1和时间3与时间1)

此测试的正确代码应该是什么?根据昨天收到的建议,我在下面尝试了一些操作,但是遇到了错误。我还认为下面的代码仅对时间2与时间1,时间3与时间2进行配对测试。这不是我想要的。

感谢您的阅读。

 library(ggplot2)
 library(ggpubr)
 library(gganimate)
 library(tidyverse)

示例数据

 structure(list(code = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 
4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 7L, 8L, 8L, 8L), diet = c("a", 
"a", "a", "b", "b", "b", "a", "a", "a", "b", "b", "b", "a", "a", 
"a", "b", "b", "b", "a", "a", "a", "b", "b", "b"), time = c(1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 
3L, 1L, 2L, 3L, 1L, 2L, 3L), bicep = c(8L, 7L, 7L, 9L, 9L, 9L, 
11L, 10L, 9L, 11L, 11L, 12L, 12L, 11L, 10L, 9L, 9L, 9L, 12L, 
10L, 8L, 12L, 12L, 12L)), class = "data.frame", row.names = c(NA, 
-24L))

示例代码

example3 %>%
  group_by(time) %>% 
  mutate(p=pairwise.wilcox.test(example3$bicep, interaction(example3$diet, example3$time), p.adjust.method = "none")$p.value,
         max=max(bicep, na.rm = T)) %>% 
  ggplot() + 
  geom_violin(aes(x=diet, y=bicep, fill=diet)) +
  geom_text(data = . %>% distinct(p, max, time), 
            aes(x=1.5, y = max+.5, label=as.character(round(p,2))),
            size=12) +
  transition_time(time) +
  ease_aes('linear')

这是我得到的错误

 Error in mutate_impl(.data, dots) : 
  Column `p` must be length 8 (the group size) or one, not 25
In addition: There were 15 warnings (use warnings() to see them)

1 个答案:

答案 0 :(得分:0)

如果我了解您的问题,那么有一个非常简单的解决方案。您由于mutate内部语法错误而收到此错误。使用$和管道mutate时,无需使用%>%调用值:

此代码给出了所需的动画,并带有轻微警告:

example3 %>%
  group_by(time) %>% 
  mutate(p=pairwise.wilcox.test(bicep, interaction(diet, time), p.adjust.method = "none")$p.value,
         max=max(bicep, na.rm = T)) %>% 
  ggplot() + 
  geom_violin(aes(x=diet, y=bicep, fill=diet)) +
  geom_text(data = . %>% distinct(p, max, time), 
            aes(x=1.5, y = max+.5, label=as.character(round(p,2))),
            size=12) +
  transition_time(time) +
  ease_aes('linear')

enter image description here

更新

例如,对于独立的p值,您只需要添加facet_wrap()。这似乎是最简单的:

example3 %>%
  group_by(time) %>% 
  mutate(p = pairwise.wilcox.test(bicep, interaction(diet, time), p.adjust.method = "none")$p.value,
         max = max(bicep, na.rm = T)) %>%
  ggplot() + 
  geom_violin(aes(x = diet, y = bicep, fill = diet)) +
  geom_text(data = . %>% distinct(p, max, time), 
            aes(x = 1, y = max+.5, label = as.character(round(p,2))),
            size = 12) +
  facet_wrap(~diet, scales = "free_x") + # add facets
  theme(legend.position = "none") +
  transition_time(time) +
  ease_aes('linear')

enter image description here