The
but what I would like to obtain is that stratified by group, something like this:
CodePudding user response:
One way would be to use an interaction between the x
and group
variables:
library(ggplot2)
library(dplyr)
library(ggsignif)
d %>%
mutate(x2 = interaction(group, x)) %>%
ggplot(aes(x2, y, fill = group))
geom_boxplot()
geom_signif(comparisons = list(c(1, 3),
c(2, 4)),
y_position = rep(max(d$y), 2) * c(1, 1.05))
This changes the labelling on the x axis which may not be desired. To keep the axis the same as your original plot we can mimic a discrete scale by using a continuous one and setting the breaks and labels appropriately.
d %>%
mutate(x2 = as.integer(interaction(group, x))) %>%
ggplot(aes(x2, y, group = x2, fill = group))
geom_boxplot()
geom_signif(comparisons = list(c(1, 3),
c(2, 4)),
y_position = rep(max(d$y), 2) * c(1, 1.05))
scale_x_continuous(breaks = c(1.5, 3.5), labels = c("a", "b"))