Q:

Issues specifying facets within a function

I have data similar to dat1:
dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each=2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))

When I run this ggplot() call normally
ggplot(dat1, aes(x=var1, y="..density..", color = Region))+
   geom_density(aes(y=..density..))+
   facet_wrap(~Region)

But when I try to turn this into a function it doesn't work:
DensPlot <- function(dat, elm, groupvar){
  ggplot(dat1, aes_string(x=elm, y="..density..", color = groupvar))+
   geom_density(aes(y=..density..))+
   facet_wrap(~groupvar)
}
DensPlot(dat=dat1, elm="var1", groupvar = "Region")

Error: At least one layer must contain all faceting variables: `groupvar`.
* Plot is missing `groupvar`
* Layer 1 is missing `groupvar`

The function will work without facet_wrap(), only making a single plot. What can I do to get the function to work with facet_wrap()?

A:

Try to do it this way. Here is an interesting article that may be helpful.
 https://aosmith.rbind.io/2018/08/20/automating-exploratory-plots/
DensPlot <- function(dat, elm, groupvar){
  ggplot(dat, 
         aes(x=.data[[elm]],
             y="..density..", 
             color = .data[[groupvar]])) +
    geom_density(aes(y=..density..)) +
    facet_wrap(~.data[[groupvar]])}

DensPlot(dat = dat1, elm = "var1", groupvar = "Region")

