Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 aes argument

I have a function:

vis = function(df, x){
p1 <- ggplot(df, aes(x)) + geom_line(aes(y = v2))
p1
}

I have a data frame:

df = data.frame(v0 = c(1,2,3), v1 = c(2,3,4), v2 = c(3,4,5))

I want to generate plot: (1) v2 v.s. v0, (2) v2 v.s. v1.

So I tried:

vis(df, v0) // not work
vis(df, v1) // not work
vis(df, "v0") // not work
vis(df, "v1") // not work

Much appreciated any idea!

like image 902
Hanbo Avatar asked Jan 29 '23 00:01

Hanbo


1 Answers

Another method using quo_name and aes_string. This does not require dev version of ggplot2:

library(ggplot2)
library(rlang)

vis = function(df, x){
  x <- enquo(x)
  ggplot(df, aes_string(quo_name(x))) + geom_line(aes(y = v2))
}

vis(df, v0)

enter image description here

like image 80
acylam Avatar answered Feb 04 '23 20:02

acylam