Search code examples
rggplot2gganimateggpubr

Adding p-values to compare groups means at different at times in gganimate gif with boxplots/violins


My current code for printing violins using gganimate looks like this

  library(ggplot2); library(gganimate); library(ggpubr)
  ggplot(dat2, aes(x=diet, y=bicep, fill=diet)) + 
  geom_violin() +
  scale_fill_manual(values=c("#00AFBB", "#FC4E07")) +
  stat_compare_means(aes(label = ..p.format..), paired = FALSE, label.x.npc = 0.5) +
  labs(title = 'Week: {frame_time}') +
  transition_time(time) +
  ease_aes('linear')

Here the p values are printed but they are just overall p values. I would like the p-value to change over time (0, 6 and 12 weeks). In my study the each outcome measurement (bicep) is taken at three different times (0, 6 and 12 weeks or time 1, time 2, time 3), It would be neat if I could show changing p-values at time 0, 6, 12. Here I would use a unpaired t test to compare group means across diet/treatment.

Alternatively, show p-value (paired t test) just at the end where bicep at time '3' is compared to bicep at time '1' for both diets.

How would I go about doing this? Thanks for reading this.

Data Structure

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

Reproducible gganimate code

    ggplot(example3, aes(x=diet, y=bicep, fill=diet)) + 
  geom_violin() +
  scale_fill_manual(values=c("#00AFBB", "#FC4E07")) +
  stat_compare_means(aes(label = ..p.format..), paired = FALSE, label.x.npc = 0.5) +
  labs(title = 'Week: {frame_time}') +
  transition_time(time) +
  ease_aes('linear')

Solution

  • You can try to calculate the p.values in advance.

    library(gganimate)
    library(tidyverse)
    example3 %>%
      group_by(time) %>% 
      mutate(p=wilcox.test(bicep~diet, exact =F)$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

    You need to install ggpubr_0.2