ss0208535 ss0208535 - 3 months ago 42
R Question

Scale for aesthetics used in the plot | ggplot2

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.



Answer

To answer the specific question in the comments:

If you want to force specific colors, you need to use scale_color_manual. As the name suggests, this needs some manual work.

library(ggplot2)

#default colors
#http://stackoverflow.com/a/8197703/1412059
gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

ggplot(mpg, aes(displ, hwy)) + 
  geom_point(aes(colour = class)) + 
  geom_smooth(method = "lm", se = FALSE, aes(color = "model")) +
  scale_color_manual(values = setNames(c(gg_color_hue(length(unique(mpg$class))), "red"),
                                       c(unique(mpg$class), "model")))

resulting plot

However, I would use an additional aesthetic for the line type.

ggplot(mpg, aes(displ, hwy)) + 
  geom_point(aes(colour = class)) + 
  geom_smooth(method = "lm", se = FALSE, aes(linetype = "model"), color = "red")

second resulting plot