Home > other >  Pass a column name as a function parameter with aes_str
Pass a column name as a function parameter with aes_str

Time:11-09

I am trying to overlay two density plots, one by condition and one as total density. I am able to do this using the following code.

ggplot(mtcars)  
  geom_density(aes(mpg))  
  geom_density(aes(mpg, after_stat(count) * 0.01, 
                   group = cyl, fill = as.character(cyl)), alpha = 0.2)

What I would like to do is turn this into a function where the column to be used can be passed as a parameter. I am able to do this with ggplot(mtcars) geom_density(aes_string(column)) but I cannot make it work with the second part of the graph.

CodePudding user response:

Perhaps this is what you are looking for: You could use dplyr's curly-curly-operator:

library(dplyr)
libary(ggplot2)

my_function <- function(data, column_1, column_2) {
  ggplot(data)  
    geom_density(aes({{ column_1 }}))  
    geom_density(aes({{ column_1 }}, after_stat(count) * 0.01, 
                     group = {{ column_2 }}, fill = as.character({{ column_2 }})), alpha = 0.2)
}

So my_function(mtcars, mpg, cyl) returns

a ggplot2 plot

  • Related