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,524
  • 2
  • 24
  • 36

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
  • 53,097
  • 5
  • 97
  • 100
  • `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