I am an absolute beginner in ggplot2. I got frustrated with ggplot2 and started reading Wickham's awesome book. He says that "a scale is required for every aesthetic used on the plot.".
So, I did the following:
Try 1:
huron <- data.frame(year = 1875:1972, level = as.numeric(LakeHuron))
ggplot(huron, aes(year)) +
geom_line(aes(y = level + 5, color = "y+5")) +
scale_color_manual(values = c("orange")) +
geom_line(aes(y = level - 5, color = "y-5")) +
scale_color_manual(values = "blue")
Upon running this, I get an error saying " insufficient value of colors provided."
I googled this and found the following thread on SO : ggplot2 Error: Insufficient values in manual scale. In original post, it makes sense why he/she added extra colors. However, I am not sure why this would be the case in my example because I have two layers, each with its own aesthetic.
Try 2
This code will work: (as in I can see two line plots in two different color and a legend--this is my objective)
ggplot(huron, aes(year)) +
geom_line(aes(y = level + 5, color = "y+5")) +
scale_color_manual(values = c("orange", "blue")) + #Added another color here.
geom_line(aes(y = level - 5, color = "y-5"))
Surprisingly, the above code shows something weird--I have got two aesthetics and only one scale.
Question 1: This is quite surprising because as we can see that there are two geoms but only one scale. Correct? I know Wickham cannot be wrong. So, what am I missing?
Question 2: Also, out of curiosity, if I have multiple geoms each with one aesthetic as in above case, and with one scale tied to each, how will ggplot know which scale ties back to which geom? As in, how would ggplot2 know whether layer1 goes with scale with color = red
and layer2 goes with color = blue
?
I'd sincerely appreciate your thoughts. Thanks in advance.