R ggplot2 aes argument

只愿长相守 提交于 2020-01-10 05:12:05

问题


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")


来源:https://stackoverflow.com/questions/50587618/r-ggplot2-aes-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!