如何设置中间横杆以在因子内对齐?

How can I set median crossbars to align within factors?

我有一个这样的数据框:

my_df <- structure(list(SampleID = c("sample01", "sample02", "sample03", 
"sample04", "sample05", "sample06", "sample07", "sample08", "sample09", 
"sample10", "sample11", "sample12", "sample13", "sample14", "sample15", 
"sample16", "sample17", "sample18", "sample19", "sample20"), 
    y = c(1.68547922357333, 0.717650914301956, 1.18156420566867, 
    1.31643130248052, 1.2021341615705, 0.946937741954258, 1.75576099871947, 
    0.952670480793451, 2.00921185693852, 0.968642950473789, 1.65243482711174, 
    2.14332269635055, 0.30556964944383, 0.860605616591314, 0.933339331803171, 
    1.31797519903504, 0.857873539291964, -0.328227710452388, 
    -0.22023346428776, 1.6600566728651), week = structure(c(1L, 
    2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 3L, 1L, 2L, 
    3L, 1L, 2L, 3L), .Label = c("0", "3", "6"), class = "factor"), 
    grumpy = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 
    2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), week_grumpy = structure(c(2L, 
    4L, 6L, 2L, 4L, 6L, 1L, 3L, 5L, 2L, 4L, 6L, 1L, 5L, 2L, 4L, 
    6L, 1L, 3L, 5L), .Label = c("0 No", "0 Yes", "3 No", "3 Yes", 
    "6 No", "6 Yes"), class = "factor")), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L))

#packages needed if you don't have
install.packages("ggbeeswarm")
install.packages("ggplot2")

我通常是这样画的:

library(ggplot2)
library(ggbeeswarm)

ggplot(data = my_df, aes(x=week, y=y, color=grumpy)) +
    geom_quasirandom(dodge.width = 0.75)

这很好,因为它很好地分离了颜色。现在,我喜欢添加中位数横杆以进一步显示组之间的差异。像这样:

ggplot(data = my_df, aes(x=week, y=y, color=grumpy)) +
    geom_quasirandom(dodge.width = 0.75) +
    stat_summary(aes(group = grumpy), fun = median, fun.min = median, fun.max = median, geom = "crossbar", color = "black", width = 0.7, lwd = 0.2)

现在,我想要的是中位数横线与 x 轴上每个因素内的颜色对齐。有没有办法在 R 中做到这一点?还是我只能手动编辑横杆以进行排列?

这是我尝试过的一件事:

ggplot(data = my_df, aes(x=week_grumpy, y=y, color=grumpy)) +
    geom_jitter(width = 0.1) +
    stat_summary(aes(group = grumpy), fun = median, fun.min = median, fun.max = median, geom = "crossbar", color = "black", width = 0.7, lwd = 0.2)

但现在 x 轴不是我想要的方式(但是,与前面的示例相比,在 Inkscape 之类的软件中手动编辑会更容易)。

我找到了一些提示 and here,但还没有找到令人满意的解决方案。

你要找的是躲避横梁geom。例如:

ggplot(data = my_df, aes(x=week, y=y, color=grumpy)) +
  geom_quasirandom(dodge.width = 0.75) +
  stat_summary(
    aes(group = grumpy), fun = median, fun.min = median, fun.max = median,
    geom = "crossbar", color = "black", width = 0.7, lwd = 0.2,

    # add this bit here to your stat_summary function
    position=position_dodge(width=0.75)
  )

看来geom_quasirandom()在这里的表现与geom_point(position=position_jitterdodge(dodge.width=0.75))非常相似。在这种情况下,由于 dodge.width 是在 geom_quasirandom() 中指定的,因此您在交叉条 geom 中对 position_dodge 使用相同的 width

注意:您可能想尝试一下美学格式,以便能够更清楚地区分横杆告诉您的内容,但这应该可以回答您的问题。