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.
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:
Thanks again, you've been very helpful!