title: Passing argument to facet grid in function -ggplot
body: <p>I am trying to write a function to plot graphs in a grid. I am using ggplot and facet grid. I am unable to pass the argument for facet grid.  I wonder if anybody can point me in the right direction.</p>
  
  <p>The data example:</p>
  
  <pre><code> Year = as.factor(rep(c("01", "02"), each = 4, times = 1))
   Group = as.factor(rep(c("G1", "G2"), each = 2, times = 2))
   Gender = as.factor(rep(c("Male", "Female"),   times = 4))
   Percentage = as.integer(c("80","20","50","50","45","55","15","85"))
   df1 = data.frame (Year, Group, Gender, Percentage)
  </code></pre>
  
  <p>The code for the grid plot without function is:</p>
  
  <pre><code>p = ggplot(data=df1, aes(x=Year, y=Percentage, fill = Gender)) + geom_bar(stat = "identity")
  p = p +  facet_grid(~ Group, scales = 'free')  
  p
  </code></pre>
  
  <p>This produces a plot like the ones I want to do. However, when I put it into a function:</p>
  
  <pre><code>MyGridPlot &lt;- function (df, x_axis, y_axis, bar_fill, fgrid){
  p = ggplot(data=df1, aes(x=x_axis, y=y_axis, fill = bar_fill)) + geom_bar(stat = "identity")
  p = p +  facet_grid(~ fgrid, scales = 'free')  
  return(p)
  }
  </code></pre>
  
  <p>And then run:</p>
  
  <pre><code>MyGridPlot(df1, df1Year, df1$Percentage, df1$Gender, df1$Group)
  </code></pre>
  
  <p>It comes up with the error:</p>
  
  <pre><code>Error: At least one layer must contain all faceting variables: `fgrid`.
  * Plot is missing `fgrid`
  * Layer 1 is missing `fgrid
  </code></pre>
  
  <p>I have tried using <code>aes_string</code>, which works for the x, y and fill but not for the grid.</p>
  
  <pre><code>MyGridPlot &lt;- function (df, x_axis, y_axis, bar_fill, fgrid){
  p = ggplot(data=df1, aes_string(x=x_axis, y=y_axis, fill = bar_fill)) + geom_bar(stat = "identity")
  p = p +  facet_grid(~ fgrid, scales = 'free')  
  return(p)
  }
  </code></pre>
  
  <p>and then run:</p>
  
  <pre><code>MyGridPlot(df1, Year, Percentage, Gender, Group)
  </code></pre>
  
  <p>This produces the same error. If I delete the facet grid, both function code runs well, though no grid :-(</p>
  
  <p>Thanks a lot for helping this beginner.</p>
  
  <p>Gustavo</p>