Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing color as a variable to aes_string

Tags:

r

ggplot2

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.

like image 456
Dronacharya Avatar asked Dec 18 '13 05:12

Dronacharya


1 Answers

The reason for the error is pretty self-explanatory: D2 is not present in the original dataset. Note that you can map colour directly to your variable D, so your colorName construction is redundant. Check this out:

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

Note that to properly map colour, you need to convert it to factor first. enter image description here

UPD: Well, let me show you how to get rid of the for loop, which is generally not a good practice.

library(reshape2)
melt.plotdata <- melt(plotdata, id.vars=c("SpaceWidth", "D"))
melt.plotdata <- melt.plotdata[order(melt.plotdata$SpaceWidth), ]
melt.plotdata <- na.omit(melt.plotdata)
q <- ggplot(melt.plotdata, aes(SpaceWidth, value, colour=variable)) + geom_path()
q + scale_colour_manual("Legend", 
                        values = c("blue", "red", "green", "violet", "yellow")) +
  scale_x_log10(breaks = melt.plotdata$SpaceWidth) +
  facet_wrap(~ D, ncol = 3) + 
  labs(title = "Fu plot", y = "MTN")

The plot will be identical to the one I posted above.

like image 191
tonytonov Avatar answered Oct 21 '22 06:10

tonytonov