I want to use facet_grid with stat_compare_means and have individual scales for y. I thought scale = "free" would take care of it, but it doesn't. Level "B" in my Name factor is not scaled properly.
library(tidyverse)
library(ggpubr)
set.seed(2)
my_comparisons <- list(c("Cond1","Cond2"),
c("Cond2","Cond3"),
c("Cond1","Cond3"))
nrName <- 4
nrCond <- 3
nrValue <- 5
Name <- rep(c("A","B","C","D"),each=nrValue*nrCond)
Condition <- rep(c("Cond1","Cond2","Cond3"),length.out=nrName*nrCond*nrValue)
Score <- c(rnorm(nrValue*nrCond,6,1),rnorm(nrValue*nrCond,0.01,0.01),rnorm(nrValue*nrCond,7,1),rnorm(nrValue*nrCond,7,1))
df <- data.frame(Name = Name, Condition = Condition, Score = Score)
plt <- ggplot(df,
aes(x= Condition,y= Score, fill= Condition))+
#geom_flat_violin(position = position_nudge(x = .2),adjust = 2)+
geom_point(position = position_jitter(width = .15), size = .25)+
geom_boxplot(outlier.shape = NA, alpha = 0.3, width = .1, colour = "BLACK") +
facet_grid(reformulate("Name","."),scales = 'free')+
scale_y_continuous(expand = expansion(mult = c(0, 0.1)))+
stat_compare_means(
comparisons = my_comparisons,
method = "t.test",paired = TRUE,
label.y.npc = 0.1)
print(plt)
I thought it might be related to the labels in stat_compare_means. But removing stat_compare_means yields similar result.
What am I not considering here?
I see my confusion now. As RonakShah pointed out correctly, I use geom_flat_violin from the the PupillometryR in my original code. I wanted to simplify the problem when I wrote the post here which is the reason why I showed the boxplots. If I add the line with the geom_flat_vioilin back in, and use greom_wrap as suggested by Suren, the scale = "free" option doesn't work anymore.
ggplot(df,
aes(x= Condition,y= Score,fill= Condition))+
geom_flat_violin(position = position_nudge(x = .2))+
geom_point(position = position_jitter(width = .15), size = .25)+
geom_boxplot(outlier.shape = NA, alpha = 0.3, width = .1, colour = "BLACK") +
facet_wrap(reformulate("Name","."),scales = 'free',nrow = 1)+
scale_y_continuous(expand = expansion(mult = c(0, 0.1)))
I guess I have to check out the geom_flat_violin function for further debuging.
geom_flat_violin
from? – Ronak Shahgeom_flat_violin
-facet_wrap
works fine otherwise. – Suren