R,ggplot: Plot x-axis as a numeric timepoint but use stat_compare_means to compare between timepoints

Viewed 65

I want a combo of these two plots essentially, which use the EXACT same data. The first plots separation on x axis combined with the stats from stat compare means seen in second plot.

I want this x axis separation And i want to be able to show the stats

With ggplot I want to plot a barplot with "time" on the x axis. For values not to be equidistant this requires "time" to be a numeric. However i also want to perform a t.test between the "times" with something like stat_compare_means. This however requires a categorical variable. As far as i can tell you have to pick. Either you can use stat_compare_means with your x axis variable as categorical and hence ur "times" will be equidistant on the x axis, or you can make them a numeric in which case you cant use stat compare means. Surely there has to be a way to do both together as it is so fundamental. I have tried multiple ways and workarounds and always encounter errors. Below hour is a numeric. Any ideas? I am sure it is an easy fix and i will slap myself but I'm stuck.

    library(ggpubr)
    ggbarplot(data,x="hour",y="signal",color="some_factor",
    facet.by="some_other_factor",add=c("mean_se","point"),scales="free")+ 
    rotate_x_text(55)+ 
    stat_compare_means(mapping = aes(group=hour),method="t.test",
    label="p.signif",
    comparisons = list(c(17,28),c(28,40),c(40,51),c(51,72),c(72,120)  ))  

I also tried making hour a factor and then using scale_x_continuous but that doesnt work either.

tldr: In summary i want a numeric x axis but also be able to perform stats between the x axis points as if they were factor levels.

1 Answers

Something like this should work as long as your x-axis values are integers:

dat <- data.frame(
  x = rep(c(1,3,6), each=10),
  y = c(rnorm(10,5,1), rnorm(10,5,1), rnorm(10,10,1))
)

dat %>%
  mutate(
    f_x = factor(as.character(x), levels=seq(min(x),max(x),by=1))
  ) %>%
  ggbarplot(x="f_x",y="y",add=c("mean_se","point")) +
  scale_x_discrete(drop=F, breaks=unique(dat$x)) +
  stat_compare_means(mapping = aes(group=x),method="t.test",
                     label="p.signif",
                     comparisons = list(c(1,3),c(3,6) ))

enter image description here

Related