代码之家  ›  专栏  ›  技术社区  ›  thomasfedb

在R中显示每组的多个方框图

  •  -2
  • thomasfedb  · 技术社区  · 11 年前

    我有以下形式的数据:

    Day A   B
    1   1   4
    1   2   5
    1   3   6
    2   2   2
    2   3   4
    2   5   6
    3   6   7
    3   4   6
    

    我想在一张图表上显示这一点 Day 沿着x轴,并且每个x位置具有 A B (颜色编码)。

    2 回复  |  直到 11 年前
        1
  •  3
  •   MrFlick    6 年前

    下面是一个示例的(轻微)修改 ?boxplot 帮助页。这些示例展示了函数的许多常见用法。

    tg <- data.frame(
       dose=ToothGrowth$dose[1:30], 
       A=ToothGrowth$len[1:30], 
       B=ToothGrowth$len[31:60]
    )
    head(tg)
    #   dose    A    B
    # 1  0.5  4.2 15.2
    # 2  0.5 11.5 21.5
    # 3  0.5  7.3 17.6
    # 4  0.5  5.8  9.7
    # 5  0.5  6.4 14.5
    # 6  0.5 10.0 10.0
    
    boxplot(A ~ dose, data = tg,
            boxwex = 0.25, at = 1:3 - 0.2,
            col = "yellow",
            main = "Guinea Pigs' Tooth Growth",
            xlab = "Vitamin C dose mg",
            ylab = "tooth length",
            xlim = c(0.5, 3.5), ylim = c(0, 35), yaxs = "i")
    boxplot(B ~ dose, data = tg, add = TRUE,
            boxwex = 0.25, at = 1:3 + 0.2,
            col = "orange")
    legend(2, 9, c("A", "B"),
           fill = c("yellow", "orange"))
    

    enter image description here

        2
  •  2
  •   rnso    11 年前

    尝试:

    ddf = structure(list(Day = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L), A = c(1L, 
    2L, 3L, 2L, 3L, 5L, 6L, 4L), B = c(4L, 5L, 6L, 2L, 4L, 6L, 7L, 
    6L)), .Names = c("Day", "A", "B"), class = "data.frame", row.names = c(NA, 
    -8L))
    
    mm = melt(ddf, id='Day')
    ggplot(mm)+geom_boxplot(aes(x=factor(Day), y=value, fill=variable))
    

    enter image description here