Q:

Label line in qplot

I have a qplot that is showing 5 different groupings (denoted with colour = type) with two dependent variables each. The command looks like this:
qplot(data = data, x = day, y = var1, geom = "line", colour = type) + 
      geom_line(aes(y = var2, colour = value)

I'd like to label the two different lines so that I can tell which five represent var1 and which five represent var2.
How do I do this? 

A:

You can convert the data to a "tall" format, with melt, and use another aesthetic, such as the line type, to distinguish the variables.
# Sample data
n <- 100
k <- 5
d <- data.frame(
  day = rep(1:n,k),
  type = factor(rep(1:k, each=n)),
  var1 = as.vector( replicate(k, cumsum(rnorm(n))) ),
  var2 = as.vector( replicate(k, cumsum(rnorm(n))) )
)

# Normalize the data
library(reshape2)
d <- melt(d, id.vars=c("day","type"))

# Plot
library(ggplot2)
ggplot(d) + geom_line(aes(x=day, y=value, colour=type, linetype=variable))

