Hi Ivan,
Thanks for the clarification. Legends always come from the scales, so
you need to set up the plot in such a away that the scales know what
you want. Here's a plot that captures the essence of your problem:
huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron))
ggplot(huron, aes(year)) +
geom_line(aes(y = level - 5), colour = "blue") +
geom_line(aes(y = level + 5), colour = "red")
You have two lines from the same dataset that you want to colour
differently, and include them in the legend. In most other plotting
systems, you'd just colour the lines as above, and then add a legend
that describes which colour maps to which variable. That doesn't work
in ggplot2 because it's the scales that are responsible for drawing
legends (the colour scale in this case), and they don't know about the
values the lines should take.
What you need to do is tell the colour the scale about the two
different lines by creating a mapping from the data to the colour
aesthetic. There's no variable present in the data, so you'll have to
create one:
ggplot(huron, aes(year)) +
geom_line(aes(y = level - 5, colour = "below")) +
geom_line(aes(y = level + 5, colour = "above"))
This gets us basically what we want, but the legend isn't labelled
correctly, and has the wrong colours. That can be fixed with
scale_colour_manual:
ggplot(huron, aes(year)) +
geom_line(aes(y = level - 5, colour = "below")) +
geom_line(aes(y = level + 5, colour = "above")) +
scale_colour_manual("Direction", c("below" = "blue", "above" = "red"))
In your original example, this is equivalent to operating on the
molten data and using geom_line(aes(colour = variable), data = molten)
Does that help? I'll include something like this in the next version
of the book, probably in the manual scale section.
Regards,
Hadley
--
http://had.co.nz/