keenan
keenan

Reputation: 504

Pass a column name as a function parameter with aes_str

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.

Upvotes: 2

Views: 135

Answers (1)

Martin Gal
Martin Gal

Reputation: 16988

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

Upvotes: 1

Related Questions