Is there away to add a conditional aes to a ggplot?
I am trying to build a function that generates a kernel plot but I want allow the function user the option to toggle weights on and off. I know I could write it as
if ( toggle_on = TRUE) { ggoplot with weighting) else if (toggle_on = FALSE) {ggplot without weights)
But I don't like this because I have to copy the plot code twice which gives an opportunity for the versions of the plot with and without weights to diverge if someone else later on changes one and forgets to change the other.
I would prefer a solution like this:
ggplot(plot_data, aes(x=value)) +
geom_density(aes( if(toggle_on = TRUE){weights = weight_value}))
This is the actual code for my plot unconditioned and with weights.
ggplot(plot_data, aes(x=value, color=!!sym(plot_type))) +
geom_density(aes(y=after_stat(count), weight = !!sym(pop_units)), kernel="epanechnikov", bw=5, linewidth = 1)