Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Combining group, color and linetype

Tags:

r

ggplot2

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?

like image 367
mat Avatar asked Dec 02 '18 15:12

mat


1 Answers

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.

like image 54
Julius Vainora Avatar answered Sep 30 '22 09:09

Julius Vainora