Roxana
Roxana

Reputation: 1

How to add p values into grouped charts in ggplot?

When I want to add p values into my plots:

library(tidyverse)
library(ggpubr)
library(rstatix)

 stat.test3 <- MP %>%
    group_by(TBI) %>%
    wilcox_test(age ~ mp_1) %>%
    adjust_pvalue(method = "bonferroni") %>%
    add_significance("p.adj")%>%
  mutate(y.position = 35)

 C2<-  ggplot(data=MP, aes(x=TBI, y=age, fill=mp_1))+
    geom_violin()+
    geom_boxplot(width=.2, fatten=NULL, position = position_dodge(0.9))+
    stat_summary(fun="median", geom="point", position = position_dodge(0.9))+
    stat_summary(fun.data = "mean_se", geom = "errorbar", width=.1, position = position_dodge(0.9))+
      scale_fill_brewer(name="Mind-pop", palette = "Accent")

  C2+ stat_pvalue_manual(stat.test3, xmin = "TBI",xmax = NULL)

it gives me this error:

Error in FUN(X[[i]], ...) : object 'mp_1' not found This error is shown after adding stat_pvalue to the object. How should I fix it?

Upvotes: 0

Views: 780

Answers (1)

gregor-fausto
gregor-fausto

Reputation: 660

I'm not familiar with ggpubr so can't say I understand the underlying issue but it seems like color=mp_1 instead of fill=mp_1 might fix your issue. This is in the following line:

C2 <- ggplot(data=MP, aes(x=TBI, y=age, color=mp_1)).

The full code is below. I've also changed y.position so that the significance is at the top of the plot.

MP <- structure(list(age = c(55L, 54L, 56L, 60L, 55L, 53L, 61L, 56L, 
                             58L, 58L, 56L, 58L, 58L, 58L, 59L, 57L, 56L, 60L, 57L, 58L, 61L, 
                             60L),
                     mp_1 = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 
                            2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"), 
                     TBI = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("HC", 
                "TBI"), class = "factor")), class = "data.frame", row.names = c(NA, -22L))

library(tidyverse)
library(ggpubr)
library(rstatix)
    
stat.test3 <- MP %>%
  group_by(TBI) %>%
  wilcox_test(age ~ mp_1) %>%
  adjust_pvalue(method = "bonferroni") %>%
  add_significance("p.adj") %>%
  mutate(y.position = 61.5)

C2 <-  ggplot(data=MP, aes(x=TBI, y=age, color=mp_1))+
  geom_violin() +
  geom_boxplot(width=.2, fatten=NULL, position = position_dodge(0.9))+
 stat_summary(fun="median", geom="point", position = position_dodge(0.9))+
 stat_summary(fun.data = "mean_se", geom = "errorbar", width=.1, position = position_dodge(0.9))+
 scale_fill_brewer(name="Mind-pop", palette = "Accent")

C2 + stat_pvalue_manual(stat.test3, xmin = "TBI",xmax = NULL)

enter image description here

Upvotes: 0

Related Questions