mat
mat

Reputation: 2617

ggplot2: Combining group, color and linetype

I have a data base with 3 factors (condition, measure and time) and would like to plot them using the x-axis, the color/group and the linetype.

As an exemple, my data looks like this:

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

My goal is to draw a graph like this:

enter image description here

I tried:

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

But it returns this error:

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

What am I missing?

Upvotes: 12

Views: 8605

Answers (2)

Julius Vainora
Julius Vainora

Reputation: 48241

You want to use

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

enter image description here

because the actual grouping is not only by measure but also by condition. When grouping by measure alone, I guess it's asking for kind of parallelograms rather than lines.

Upvotes: 19

hrbrmstr
hrbrmstr

Reputation: 78832

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

enter image description here

Upvotes: 4

Related Questions