R: ggplot2: A referential transparency problem

34 views Asked by At

The function below is a character by character exact copy of a function appearing on page 26 of the second edition of Hadley Wickham's ggplot2 book, with two exceptions:

  1. The output is assigned to p, which is then plotted.
  2. The expression following "colour = " in the original was "year(date)".

If you take year(economics$date), you get a numeric vector running from 1967 to 2015, inclusive, by ones. I have replaced that expression with 1967:2015. The result is an error:

Error: Aesthetics must be either length 1 or the same as the data (574): colour

I have two questions.

year <- function(x) as.POSIXlt(x)$year + 1900

p <- ggplot(economics, aes(unemploy / pop, uempmed)) + 
  geom_path(colour = "grey50") + 
  geom_point(aes(colour = 1967:2015))

plot(p)
  1. Why on earth does this trivial change break the function?
  2. Why did the function work in the first place? (It does). Because if you look at the documentation for the colour esthetic, here: https://ggplot2.tidyverse.org/articles/ggplot2-specs.html it does not say that the colour esthetic takes either a numerical vector or a function.
0

There are 0 answers