I want to use a variable for the legend key label in a ggplot chart that uses two geom_line plots and scale_colour_manual. If I explicitly use strings to define the legend key label, everything works fine, just as per section 6.4.4. in hadley’s book, p.109.

If on the other hand I pop the label in a variable and use the variable in the geom_line and scale_colour_manual calls, nothing happens.

As you can see, plot ‘p1’ works just fine. Plot ‘p2’ does not show the two line plots, although it does show the correct key labels. The code used to generate the two plots is given below. (The background to this request is that I want to pass legend key labels to a wrapper function.)
Q. Why does the approach used in p2 below not work? How can I use variables to define the key labels and to link them to the correct colours in the key labels?
require(ggplot2)
require(lubridate)
set.seed(12345)
# create dummy time series data
monthsback <- 60
startdate <- as.Date(paste(year(now()),month(now()),"1",sep="-")) - months(monthsback)
x <- data.frame(mydate=seq(as.Date(startdate), by="month", length.out=monthsback),
myval1=runif(monthsback, min=600, max=800),
myval2=runif(monthsback, min=400, max=600))
var1 <- "foo-var"
var2 <- "bar-var"
p1 <- ggplot(x, aes( mydate, myval1)) +
geom_line( aes( x = mydate, y = myval1, colour = "foo"), size = 0.5) +
geom_line( aes( x = mydate, y = myval2, colour = "bar"), size = 0.5) +
scale_colour_manual("Legend", values = c("foo" = "red", "bar" = "blue"))
print (p1)
p2 <- ggplot(x, aes( mydate, myval1)) +
geom_line( aes( x = mydate, y = myval1, colour = var1), size = 0.5) +
geom_line( aes( x = mydate, y = myval2, colour = var2), size = 0.5) +
scale_colour_manual("Legend", values = c(var1 = "red", var2 = "blue"))
#print (p2)
I do this a lot, as I use a lot of “standardized” plot options. I’m sure there’s a more elegant way to dig in to the proto object but the result is the same take a look at
str(tmp)and you’ll have a better understanding of what is being mapped:As an aside, you can save ggplot + ggplot elements to a list and then edit the list items programatically (kind of like what I’ve done above).
For example: