【问题标题】:how to plot multiple box plots on one graph using ggplot如何使用ggplot在一张图上绘制多个箱线图
【发布时间】:2016-06-24 02:32:28
【问题描述】:

我正在运行以下代码行

 bp <- ggplot(data, aes(x = Month, y = days, group = Month)) + geom_boxplot()+facet_wrap(~Depth)

它工作得很好,并产生了一个由 3 个不同深度的 3 个图组成的图,每个图都包含每个月的箱线图(我还不能发布img

但是,我想将它们显示在一个图表上,并为 3 个变量(25、100 和 300)进行深度颜色编码。 我将如何实现这一目标? 我的数据是这样的

 depth month days
  25     1    49
  25     1    51
  100    1    52
  100    1    55 
  300    1    52
  300    1    50
  25     2    47
  25     2    48
  100    2    53
  100    2    57
  300    2    56
  300    2    59
  ...   ...  ... 

如果这是一个重复的问题,我深表歉意,但我查看的问题似乎不符合我的需求 我尝试过使用

bp + geom_boxplot(position = position_dodge(width = 0.8)) 

按照here 的建议,但没有创建一个图表

谢谢

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不确定要求“深度颜色编码”是什么意思,所以让我们从将它们“全部集中在一个图上”的要求开始。您可以使用交互功能来构造一个双向分组,该分组将获得geom_boxplot 的认可:

     bp <- ggplot(dat, aes(x = interaction(month,depth, sep=" x "), y = days)) + 
                       geom_boxplot()
     bp
    

    这可能是所要求的:

     bp <- ggplot(data, aes(x = group, y = days, 
                            group = interaction(month, depth) , colour = as.factor(depth) )) + 
              geom_boxplot() 
     bp
    

    【讨论】:

    • 感谢您的建议 42- 第一个答案看起来就是我所需要的
    • 提供的数据实际上有一个错误,它每个月应该只有 25、100 和 300,而不是相同深度的倍数
    • 如果每个因素组合只有一个值,那么使用箱线图就没有多大意义。
    • 这是我想要达到的目标ggplot(data, aes(x = factor(Month), y = days, colour = Depth)) + geom_boxplot(aes(group = group))。我的描述可能没有解释清楚
    • 或许:bp &lt;- ggplot(data, aes(x = group, y = days, group = interaction(month, depth) , colour = as.factor(depth) )) + geom_boxplot() ; bp
    【解决方案2】:

    如果我正确理解您的问题,您的任务可以通过以下代码完成,

    data <- read.table(text = "depth month days
    25     1    49
    25     1    51
    100    1    52
    100    1    55 
    300    1    52
    300    1    50
    25     2    47
    25     2    48
    100    2    53
    100    2    57
    300    2    56
    300    2    59", header = TRUE)
    

    首先,新建一个变量group

    data$group <- with(data, paste("Month:", month, ",depth:", formatC(depth, width = 3, flag = 0), sep = ""))
    

    然后绘制箱线图,你必须使用scale_colour_manual()指定颜色。

    bp <- ggplot(data, aes(x = group, y = days, group = group, colour = group)) + geom_boxplot() + scale_colour_manual(values = rep(1:3, 2))
    bp
    

    【讨论】:

    • 在我的交互式图形设备上,如果您在 month 参数后插入 "\n",paste,看起来会好很多,
    • 非常感谢!这看起来可能已经解决了我的问题,尽管我还不能让它与我的完整数据集一起工作。我想我应该能够通过一点点玩来让它工作
    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多