0

Is there a way to call a variable from a list using ggplot2? I am trying to create an interactive/all purpose script for a colleague.

This is how I usually plot something:

ggplot(df, aes(x = variable1)) + geom_histogram()

But for this script, I want something like:

plot_this_variable <- "variable1"
ggplot(df, aes(x = plot_this_variable)) + geom_histogram()

Is this possible? If so, how?

Edit:

Solution, use aes_string() instead of aes().

CAA
  • 79
  • 6

1 Answers1

2

aes_string has been deprecated, you can either use sym with !! or use .data pronoun.

library(ggplot2)
#Using `sym`
ggplot(df, aes(x = !!sym(plot_this_variable)) + geom_histogram()

#Using .data
ggplot(df, aes(x = .data[[plot_this_variable]])) + geom_histogram()

However, .data is now the preferred way.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213