1

I am building a plot with ggplot but I do not know the name of the y column in advance. Instead the name of the y column is contained in the variable yname. This obviously doesn't work:

ggplot(df, aes(x=date, y=yname))

Because ggplot looks for a column in df that is literally named "yname". How can I pass the name of the y column to ggplot as a variable?

andrew
  • 2,378
  • 2
  • 22
  • 35

1 Answers1

5

Using aes_string:

library(ggplot2)
yname <- "a"
df <- data.frame(x=runif(10), a=runif(10))
ggplot(df, aes_string(x="x", y=yname)) + geom_point()
lukeA
  • 50,755
  • 5
  • 83
  • 91
  • `aes_string` is soft deprecated. See https://stackoverflow.com/a/55133909/5477070 for a more up to date answer. – jarauh Feb 22 '21 at 18:28