How to map color and linestyle to several columns in a ggplot2 lineplot

1.6k views Asked by At

I have a data.frame with four cohorts C1-C4 that have been measured five times M1-M5.

library(ggplot2)
mydf <- data.frame(C1=c(49, 14, 8, 7, 2),
                   C2=c(0, 0, 0, 0, 0),
                   C3=c(13, 17, 7, 8, 8),
                   C4=c(0, 0, 0, 0, 0),
                   M = c("M1", "M2", "M3", "M4", "M5"))

I'd like to plot a line for each cohort showing the measurements.

ggplot(data=mydf) + 
    geom_line(aes(x=M, y=C1, group=1), colour="red") + 
    geom_line(aes(x=M, y=C2, group=2), colour="green") + 
    geom_line(aes(x=M, y=C3, group=3), colour="blue") +
    geom_line(aes(x=M, y=C4, group=4), colour="black", linetype="dashed")

I managed to do so, by manually grouping the lines. However, I have trouble with the legend. I figure I need to map color and linestyle to some grouping criteria. But how do I do this? I should group by cohort, but they are not inside one column. Is there a way to construct a legend using this manual grouping or another way to construct my plot? Any help would be greatly appreciated.

2

There are 2 answers

0
sthesing On BEST ANSWER

Thanks, everyone, that greatly helped. I struggled a little with controling the linetype and the colours, because I needed the black dotted line to overlay the green solid line. But it worked out, in the end:

library(ggplot2)
library(reshape2)

mydf <- data.frame(M = c("M1", "M2", "M3", "M4", "M5"),
                   C1=c(49, 14, 8, 7, 2),
                   C2=c(0, 0, 0, 0, 0),
                   C3=c(13, 17, 7, 8, 8),
                   C4=c(0, 0, 0, 0, 0))
mydf2 <- melt(mydf)
ggplot(data=mydf2) +
    geom_line(aes(x=M, y=value, group=variable, colour=variable, linetype=variable)) +
    scale_linetype_manual(values=c("solid", "solid", "solid", "dashed")) + 
    scale_colour_manual(values=c("red", "green", "blue", "black"))

Thanks again, you've been very helpful!

2
Matt74 On

Here's an example of what eipi10 suggested:

mydf <- data.frame(C1=c(49, 14, 8, 7, 2),
                   C2=c(0, 0, 0, 0, 0),
                   C3=c(13, 17, 7, 8, 8),
                   C4=c(0, 0, 0, 0, 0),
                   M = c("M1", "M2", "M3", "M4", "M5"))

mydf.m <- melt(mydf, id.vars="M", 
               variable.name="my_var_name", 
               value.name="my_value_name")

mydf.m$linetype_var <- ifelse(mydf.m["my_var_name"]=="C4","dashed","solid")

my_colors <- c("red","green","blue","black")

ggplot(mydf.m, aes(x=M, y=my_value_name, 
                   group=my_var_name,
                   color=my_var_name, 
                   linetype=linetype_var))+
  geom_line()+
  scale_linetype_identity()+
  scale_color_manual(values=my_colors)