在连续的x轴上按组填充和躲避箱形图

时间:2017-07-14 10:43:37

标签: r plot ggplot2 grouping boxplot

我遇到了一些似乎很简单的问题:带有连续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()

enter image description here

这是我在x连续离开时所得到的,没有分组:

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

enter image description here

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

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

enter image description here

要明确的是,geom_point中我想要的是:

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

enter image description here

...但如果我尝试在boxplot中设置闪避:

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

enter image description here

任何提示?我试过四处寻找:this question处理连续的箱形图,但没有着色问题; this question让我想知道我是否需要设置交互,但似乎没有得到预期的结果。任何帮助都将非常感激!

2 个答案:

答案 0 :(得分:7)

来自?aes_group_order

  

默认情况下,该组设置为所有离散变量的交互   曲线图。

在您的数据中,您只有一个离散变量,&#34; fill&#34;。但是,我们希望数据按 &#34;填充&#34; &#34; x&#34;。因此,我们需要使用group参数指定所需的分组。是的,你是对的,interaction是要走的路。

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

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

然后是情节,我们根据&#34; x&#34;的不同组合对数据进行分组。和&#34; grp&#34; (interaction(x, grp))和fill方框&#34; grp&#34;:

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

enter image description here

答案 1 :(得分:0)

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

采用原始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之间等分 Boxplot with 5 custom groups with equal cuts between 1:10