簡體   English   中英

ggplot2:組合組,顏色和線型

[英]ggplot2: Combining group, color and linetype

我有一個包含3個因素( conditionmeasuretime )的數據庫,並希望使用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

我錯過了什么?

你想用

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

在此輸入圖像描述

因為實際的分組不僅是通過measure而且是通過condition 當單獨按measure分組時,我猜它要求的是平行四邊形而不是線條。

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)
  )

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM