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

在ggplot中绘制多个组的成对数据

  •  0
  • Jeff238  · 技术社区  · 3 年前

    set.seed(123)
    sample <- data.frame(name = c(rep("Amy",4),rep("Bob",4),rep("Jack",4)),
                         status = rep(c("Before","After"),6),
                         test = rep(c("English","English","Math","Math"),3),
                         score = sample(60:100,12,replace=T))
    sample %>% ggplot(aes(x=test,y=score,fill=status)) + 
      geom_boxplot() + geom_point(size = 2)
    

    我们的想法是 test 在x轴和 score geom_point() status 分组(以便在 after 组位于红色方框图所在的空间和 before 组位于蓝色箱线图所在的空间)中 geom_line() name . 谢谢

    enter image description here

    0 回复  |  直到 3 年前
        1
  •  1
  •   huchzi    3 年前

    最简单的方法是使“状态”成为x-美学,并使用镶嵌面包裹分离测试:

    ggplot(sample, aes(x = status, y = score)) + 
    geom_boxplot(aes(fill = status), alpha = .2) +
    geom_line(aes(group = name)) + 
    geom_point(size = 2) + 
    facet_wrap(~ test)
    

    Plot with boxplot and line

    ggplot(sample, aes(x = status, y = score, group = name)) + 
    geom_line() + 
    geom_point(size = 2, aes(color = status)) + 
    facet_wrap(~ test, switch = "x") +
    scale_x_discrete("") +
    theme_minimal() +
    theme(legend.position = "top", 
          panel.grid = element_blank(),
          axis.text.x = element_blank(),
          axis.line.y = element_line(size = .5))
    

    enter image description here