Resources for writing functions that use ggplot2

1,518 views
Skip to first unread message

Bryan Hanson

unread,
Jan 24, 2013, 12:34:55 AM1/24/13
to ggp...@googlegroups.com
I'm wondering if anyone knows of resources (guides, tips) for writing functions that use ggplot2 functions. I'm particularly interested in ways to get around or avoid scoping issues with respect to aesthetics, along the lines of my recent questions on SO:

http://stackoverflow.com/questions/14348781/ggplot2-inside-function-with-a-2nd-aesthetic-scoping-issue
http://stackoverflow.com/questions/14383207/stat-summary-different-behavior-between-qplot-ggplot2-understanding-the-par
http://stackoverflow.com/questions/14391183/ggplot2-annotation-custom-gives-an-empty-layer

Thanks! Bryan

Winston Chang

unread,
Jan 24, 2013, 1:22:12 AM1/24/13
to Bryan Hanson, ggp...@googlegroups.com
You're probably running into this bug:

In short, the aes() is evaluated in the global environment, instead of the calling environment. So if you have a function that does some stuff and then calls ggplot(), the aes gets evaluated in the global environment rather than the function's environment.

The workaround is to specify environment, as in:
  ggplot(..., environment = environment())


-Winston



--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility

To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

Bryan Hanson

unread,
Jan 24, 2013, 8:13:50 AM1/24/13
to Winston Chang, ggp...@googlegroups.com
Thank you Winston.  This is something concrete that I can experiment with.

I had actually come across this environment suggestion last night on SO (see the accepted answer & comments):


and began to ponder it.  I've been trying to get my functions so they don't give errors or warnings under 0.9.3 for a couple of weeks off and on now.  I'd reached the conclusion that my previous versions worked only by Pure Luck and that I really didn't/don't know how ggplot2 worked (other than things were not what they appeared to be when you moved from the command line to the function environment).  So I'm going to go back through with fresh eyes and see if I can figure out what's going on.

Bryan

Tom

unread,
Feb 24, 2014, 4:35:40 PM2/24/14
to ggp...@googlegroups.com
Thank you, both. I have been running up against the same problem for the last couple of days, and calling ggplot() with environment = environment() fixed it.

Regards,

Tom

Branislav Misovic

unread,
Aug 31, 2015, 7:42:41 PM8/31/15
to ggplot2, han...@depauw.edu

just to  thank you Winston... took me a while to find your solution

Reply all
Reply to author
Forward
0 new messages