首页 文章

使用ggplot2,我如何仅通过用于创建分组箱图的两个因子之一来标记x轴?

提问于
浏览
1

我认为我的问题很简单,但谷歌搜索和大惊小怪让我无处可去 . 希望有人可以提供帮助 . 我有三年内从两个不同治疗组收集的数据 . 我想为治疗和年份的每个组合生成一个箱线图(以查看治疗效果是否按年份变化) . However, I can't figure out how to label the x axis the way I want to using ggplot2.

这里有一些代码可以创建一些类似于我自己的伪造数据 .

fakeX = factor(rep(c(0,1), times=60))
fakeY = factor(rep(c(1,2,3), each=40))
fakeZ = round(runif(120, 0, 12), digits=1)
df1 = data.frame(fakeX, fakeY, fakeZ)
df1$inter = interaction(df1$fakeX, df1$fakeY)

ggplot(df1, aes(x=inter, y = fakeZ)) + 
stat_boxplot(geom='errorbar', lwd=1.75) + 
geom_boxplot(outlier.size=5, lwd = 1.75, fatten=1.25, 
fill = rep(c("dim gray", "ivory3"), times=3), aes(fill=fakeY)) +
scale_x_discrete(labels = c("2013", "", "2014", "", "2015", ""))

这段代码产生了一组像我正在寻找的箱形图:

enter image description here

到现在为止还挺好 . 然而,正如你所看到的,我已经有了用颜色标记的处理(图 Headers 将解释哪个是哪个),所以我只需要我的轴标签来说明每套两个箱图来自哪一年 . However, I can't figure out the code that will get the year labels centered exactly in between the two boxplots each is for ,这是我认为最明确的事情 . 现在,我能做的最好的事情是将年份标签与每年的第一个箱形图放在一起 . 我已经尝试在 scale_x_discrete 中使用 breaks 参数,但无济于事 . 我也尝试将 position=position_nudge() 调用传递给 scale_x_discrete ,但是没有找到,但是我必须使用反复试验才能获得每个图形所需的空间数量,而且似乎必须是一个更好的方式 . 有什么想法吗?

1 回答

  • 1

    比上面的评论更具体的例子:

    ggplot(df1,aes(x = fakeY,y = fakeZ,fill = fakeX)) + 
        stat_boxplot(geom = "errorbar",position = "dodge",lwd = 1.75) +
        geom_boxplot(position = "dodge",lwd = 1.75,fatten = 1.25,show.legend = FALSE) + 
        scale_fill_manual(values = c("dim gray", "ivory3")) + 
        scale_x_discrete(labels = c('2013','2014','2015'))
    

相关问题