Search code examples
rggplot2facet

ggstatsplot subtitle output in faceted ggplot


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:

plot

Whereas what we want is something that looks like this (except faceted):

plot2

So the questions are:

  1. Is it possible to get facet labels to interpret mtext() instructions OR
  2. Is it possible to interpret mtext() instructions outside of a plot environment and then pass this interpreted text as labels to facet_wrap/grid OR
  3. Is it possible to include a subtitle to facets separate to the label (like stat_compare_mean does) OR
  4. Other...

Solution

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