## A ggplot2 oddity

I uncovered something a little perplexing today. It helped me waste 20 minutes or so. Well, I wasted some time trying to understand the problem, but I learned something in the process. Here’s the situation (reduced to a very simple use case): I have some data and a function which calls ggplot().

That works perfectly. But suppose I define a local variable within the function and I use it to transform the plotted data.

Whoops! That breaks. The problem is that ggplot() is looking in the global environment for the variable in question. It does not see the local environment. Thanks to some helpful posts on stackoverflow, I have a solution: simply pass the local environment into the ggplot() call.

Works like a charm.