Can I use a variable rather than name inside of ggplot

I want to make a ggplot that will plot something different based on user input. That mean inside of the ggplot aes function I would like to use a variable rather than calling particular column directly from my data frame. However, I can't figure out how to get ggplot to recognize this set up.

This call works where value and bin_one are columns inside of plot_data

  kernel_plot_raw = ggplot(plot_data, aes(x=value, color=bin_one)) +
    geom_density(aes(y=after_stat(count)), kernel="epanechnikov", bw=5, linewidth = 1.5)

However when I try something like this so I can change the which column I select via the bin_type variable ggplot gets confused and plots a single line rather than dividing the kernels up by the facets inside of bin_one.

bin_type = 'bin_one'
  
kernel_plot_raw = ggplot(plot_data, aes(x=value, color=bin_type)) +
    geom_density(aes(y=after_stat(count)), kernel="epanechnikov", bw=5, linewidth = 1.5)

It appears the ggplot is treating it as a string rather than understand that it needs to pull the column with the same name.

You can use non-standard evaluation as the example below illustrates:

library(ggplot2)

ggplot(diamonds, aes(depth, colour = cut)) +
  geom_density()


bin_type <- "cut"

ggplot(diamonds, aes(depth, colour = !!sym(bin_type))) +
  geom_density()

Created on 2023-01-30 with reprex v2.0.2

It may also be useful to use aes_string().

library(ggplot2)
bin_type <- "cut"
ggplot(diamonds, aes_string("depth", colour = bin_type)) +
  geom_density()

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.