On 5/6/2014 10:25 PM, Saurabh Agrawal wrote:
> Hi
>
> Just moved to the "R" world and the awesome ggplot2 library. :)
>
> I am getting a bit confused because of an error. I am trying to use ggplot
> and thereafter ggsave inside a function, as follows:
>
> plot_dpt<-function(dpt_data.df, cols, filename){
>>
>> dpt.plot <- ggplot(dpt_data.df, aes(x=dpt_data.df[,cols[1]],
>>> y=dpt_data.df[,cols[2]])) +
This should be
dpt.plot <- ggplot(dpt_data.df, aes_string(x=cols[1], y=cols[2])) +
There are two aspects that were wrong. The first is that inside the aes
call, the mapping between aesthetics and variables should be to the
variable names that are in the provided data frame, not to vectors. So
the dpt_data.df should not appear inside the aes call. It should look like
aes(x=time, y=count)
(the aes call is not by itself; I am showing just it because the other
parts of the ggplot call are not relevant) where time and count are
names of columns in the given data frame.
That leads to the second aspect. When you have the name of the column
that you want to use in a variable rather than the bare name, you need
to use aes_string. The equivalent of the previous example is
cols <- c("time", "count")
aes_string(x=cols[1], y=cols[2])