I'm trying to add the output of grouped_ggbetweenstats() to a faceted ggplot. This similar question here says that it is impossible, but I feel like the responder didn't quite understand the question.
group_ggbetweenstats() has an option output = "subtitle" that rather than producing a plot, produces a string representing the output of the statistical test which is to be interpreted by grDevices::mtext(). This text can then be provided to the factor you are faceting by as a label. The only part of the puzzle that seems to be missing is the evaluation by grDevices.
Example below:
library(ggplot2)
library(ggstatsplot)
mtcars1 <- mtcars
statistics <- grouped_ggbetweenstats(data = mtcars1, x = cyl, y = mpg, grouping.var = am, output = "subtitle")
mtcars1$am <- factor(mtcars1$am, levels = c(0,1), labels = statistics)
mtcars1 %>%
ggplot(aes(x = cyl, y = mpg)) +
geom_jitter() +
facet_wrap(vars(am), ncol =1, strip.position = "top")
This gives:
Whereas what we want is something that looks like this (except faceted):
So the questions are:
You just need to parse those expressions in the facet labels and this should do it:
set.seed(123)
library(ggplot2)
library(ggstatsplot)
# data
mtcars1 <- mtcars
statistics <- grouped_ggbetweenstats(data = mtcars1, x = cyl, y = mpg, grouping.var = am, output = "subtitle")
mtcars1$am <- factor(mtcars1$am, levels = c(0,1), labels = statistics)
# plot
mtcars1 %>%
ggplot(aes(x = cyl, y = mpg)) +
geom_jitter() +
facet_wrap(vars(am), ncol =1, strip.position = "top", labeller = ggplot2::label_parsed)
Created on 2020-07-18 by the reprex package (v0.3.0)