R ggplot2 aes argument

2020-02-14 04:59发布

问题:

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!

回答1:

If we are passing an unquoted string, then convert it to quosure and then evaluate (!!)

library(rlang)
library(ggplot2)#devel version

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

If we pass x as strings, then replace aes with aes_string



回答2:

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)



回答3:

You can use the the name of the column:

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

vis = function(df, x){
  p1 <- ggplot(df, aes(df[,x])) + 
    geom_line(aes(y = v2))+xlab(x)
  p1
}
vis(df, "v0")