【问题标题】:ggplot2: Combining group, color and linetypeggplot2:组合组、颜色和线型
【发布时间】:2018-12-02 15:36:12
【问题描述】:

我有一个包含 3 个因子(condition、measure 和 time)的数据库,并希望使用 x 轴、颜色/组和线型来绘制它们。

例如,我的数据如下所示:

DT <- data.frame(condition = rep(c("control", "experimental"), each = 4),
                 measure = rep(c("A", "A", "B", "B"), 2),
                 time = rep(c("pre-test", "post-test"), 4),
                 score = 1:8)

> DT
     condition measure      time score
1      control       A  pre-test     1
2      control       A post-test     2
3      control       B  pre-test     3
4      control       B post-test     4
5 experimental       A  pre-test     5
6 experimental       A post-test     6
7 experimental       B  pre-test     7
8 experimental       B post-test     8

我的目标是画出这样的图表:

我试过了:

ggplot(DT, aes(time, score, group = measure, color = measure, linetype = condition)) +
    geom_line() +
    geom_point()

但它返回此错误:

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

我错过了什么?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你想用

    ggplot(DT, aes(time, score, group = interaction(measure, condition), 
                   color = measure, linetype = condition)) +
      geom_line() + geom_point()
    

    因为实际分组不仅是measure,还有condition。当单独按measure 分组时,我猜它要求的是平行四边形而不是直线。

    【讨论】:

      【解决方案2】:
      data.frame(
        condition = rep(c("control", "experimental"), each = 4),
        measure = rep(c("A", "A", "B", "B"), 2),
        time = rep(c("pre-test", "post-test"), 4),
        score = 1:8
      ) -> DT
      
      DT_wide <- tidyr::spread(DT, time, score)
      
      ggplot() +
        geom_segment(
          data = DT_wide,
          aes(
            x = "pre-test", xend = "post-test", 
            y = `pre-test`, yend = `post-test`,
            color = measure, 
            linetype = condition
          )
        ) +
        geom_point(
          data = DT,
          aes(time, score, color = measure)
        )
      

      【讨论】:

        猜你喜欢
        • 2015-10-15
        • 2015-09-25
        • 1970-01-01
        • 1970-01-01
        • 2014-10-24
        • 2015-03-09
        • 2014-12-10
        • 2013-06-15
        • 1970-01-01
        相关资源
        最近更新 更多