I’m plotting lots of similar graphs so I thought I write a function to simplify the task. I’d like to pass it a data.frame and the name of the column to be plotted. Here is what I have tried:
plot_individual_subjects <- function(var, data)
{
require(ggplot2)
ggplot(data, aes(x=Time, y=var, group=Subject, colour=SubjectID)) +
geom_line() + geom_point() +
geom_text(aes(label=Subject), hjust=0, vjust=0)
}
Now if var is a string it will not work. It will not work either if change the aes part of the ggplot command to y=data[,var] and it will complain about not being able to subset a closure.
So what is the correct way/best practice to solve this and similar problems? How can I pass column names easily and safely to functions that would like to do processing on data.frames?
Bad Joran, answering in the comments!
You want to use
aes_string, which allows you to pass variable names as strings. In your particular case, since you only seem to want to modify theyvariable, you probably want to reorganize which aesthetics are mapped in which geoms. For instance, maybe something like this:or perhaps the other way around, depending on your tastes.