简体   繁体   中英

Understanding facet_grid scale=“free”

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)

使用 stat_compare_means

I thought it might be related to the labels in stat_compare_means. But removing stat_compare_means yields similar result.

没有 stat_compare_means

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

Geom_flat_violin + geom_wrap

I guess I have to check out the geom_flat_violin function for further debuging.

Instead of facet_grid use facet_wrap for example,

facet_wrap(reformulate("Name","."), scales = 'free', nrow = 1) +

With facet_grid one can not get both x and y scales free; see here https://github.com/tidyverse/ggplot2/issues/1152

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM