Passing color as a variable to aes_string

Viewed 3196

I want to plot several columns of a data matrix against one column, so instead of plotting each column individually, I am using a loop. The problem is that the column name to be plotted and the color have to be variable if I am to use a loop. I tried the following:

allDs <- sort(unique(plotdata$D))
p <- ggplot(plotdata, aes(SpaceWidth))
for (thisD in allDs) {
    tlColName <- paste("M2D", thisD, "Tl", sep="")
    colorName <- paste("D", thisD, sep="")
    p <- p + geom_line(data = plotdata[!is.na(plotdata[[tlColName]]),], aes_string(y = tlColName, color = colorName))
}
p <- p + scale_colour_manual("Legend", values = c("D2" = "blue", "D3" = "red", "D4" = "green", "D6" = "violet", "D7" = "yellow" ))
p <- p + scale_x_log10(breaks = composite$SpaceWidth)
p <- p + facet_wrap(~ Drawn, ncol = 3)
p <- p + labs(title = "Fu plot", y = "MTN")
p

But when I run this I get the following error:

Error in eval(expr, envir, enclos) : object 'D2' not found

How can color (or any other value) be passed as a variable in aes_string? Thanks in advance.

Data for testing is available here.

1 Answers
Related