ggsave not working in a function

832 views
Skip to first unread message

Saurabh Agrawal

unread,
May 7, 2014, 1:25:07 AM5/7/14
to ggp...@googlegroups.com
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]])) + 
    geom_line(colour='#193441')
      #Save this plot
  ggsave(plot=dpt.plot,filename=paste(filename, "png", sep="."), type="cairo-png")
}

When saving I get an Error: object 'dpt_data.df' not found.

However, when I debug and set a break point at the ggsave line, I can see that dpt_data.df does contain the data frame I need there.

If someone could help this R and ggplot2 newbie, it would be great!

Thanks.

Brian Diggs

unread,
May 7, 2014, 12:06:02 PM5/7/14
to Saurabh Agrawal, public-ggplot2-/JY...@plane.gmane.org


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])
Reply all
Reply to author
Forward
0 new messages