了解 facet_grid 规模="free"

Understanding facet_grid scale="free"

我想将 facet_grid 与 stat_compare_means 一起使用,并为 y 设置单独的尺度。我认为 scale = "free" 会解决它,但事实并非如此。我的姓名因素中的“B”级未正确缩放。

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 中的标签有关。但是删除 stat_compare_means 会产生类似的结果。

我在这里没有考虑什么?

我现在明白了我的困惑。正如 RonakShah 正确指出的那样,我在原始代码中使用了 PupillometryR 中的 geom_flat_violin。当我在这里写 post 时,我想简化问题,这就是我展示箱线图的原因。如果我重新添加带有 geom_flat_vioilin 的行,并按照 Suren 的建议使用 greom_wrap,则 scale = "free" 选项不再起作用。

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 函数以进一步调试。

例如

而不是 facet_grid 使用 facet_wrap

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

使用 facet_grid 不能同时获得 x 和 y 标尺;看这里https://github.com/tidyverse/ggplot2/issues/1152