在连续的 x 轴上按组填充和闪避箱线图

Fill and dodge boxplots by group on a continuous x axis

我一直对看似简单的事情有疑问:具有连续 x 轴的分组箱线图。

这里是最小数据数据:

df <- cbind(expand.grid(x=1:10, rep=1:20, fill=c("A", "B")), y=runif(400))

这就是我想要的;你会看到我已经强制 x 轴离散:

ggplot(df, aes(x=as.factor(x), y=y,  fill=fill)) + geom_boxplot()

这是我离开 x 时得到的结果,没有分组:

ggplot(df, aes(x=x, y=y,  fill=fill)) + geom_boxplot()

当我添加分组时,颜色消失了:

 ggplot(df, aes(x=x, y=y, group=x, fill=fill)) + geom_boxplot()

明确地说,我在 geom_point 中想要的是:

ggplot(df, aes(x=x, y=y, group=x, color=fill)) + geom_point(position=position_dodge(width=.7))

...但是如果我尝试在箱线图中设置闪避:

ggplot(df, aes(x=x, y=y, color=fill)) + geom_boxplot(position=position_dodge(width=.7))

有什么建议吗?我尝试四处搜索: this question addressed continuous boxplots, but without the coloring issue; 让我想知道是否需要设置交互,但似乎没有得到想要的结果。任何帮助将不胜感激!

来自?aes_group_order

By default, the group is set to the interaction of all discrete variables in the plot.

在您的数据中,您只有一个离散变量,"fill"。但是,我们希望数据按both"fill"and"x"分组。因此,我们需要使用 group 参数指定所需的分组。是的,你是对的,interaction 是正确的选择。

首先,稍微小一点的数据集(更容易link数据输出):

d <- data.frame(x = rep(c(1, 2, 4), each = 8),
                grp = rep(c("a", "b"), each = 4),
                y = sample(24))

然后是绘图,我们按 "x" 和 "grp" (interaction(x, grp)) 的不同组合对数据进行分组,fill 框按 "grp":

ggplot(d, aes(x = x, y = y, group = interaction(x, grp), fill = grp)) +
  geom_boxplot()

这是一个有效的版本,为您自己的切割尺寸定制

取原df:

{df <- cbind(expand.grid(x=1:10, rep=1:20, fill=c("A", "B")), y=runif(400))}

使用 cut() 定义您想要 x 组的位置并使用 "dodge2" 定位您的图表:

{ggplot(df, aes(x = cut(x, 5), y = y, fill = fill)) +
        geom_boxplot(position = "dodge2", outlier.alpha = 0.1)}

具有 5 个自定义组的箱线图,在 1:10 之间具有相等的切割