passing parameters to ggplot

前端 未结 4 1407
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 03:00

would like to create a function that generates graphs using ggplot. For the sake of simplicity, the typical graph may be

ggplot(car, aes(x=speed, y=dist)) +          


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 03:29

    One approach that I can think of is using match.call() to reach the variable names contained by the parameters/arguments passed to the custom plotting function and then use eval() on them. In this way you avoid passing them as quoted to your custom function, if you do not like that.

    library(ggplot2)
    
    fun <- function(df, x, y) {
        arg <- match.call()
        ggplot(df, aes(x = eval(arg$x), y = eval(arg$y))) + geom_point()
    } 
    fun(mpg, cty, hwy) # no need to pass the variables (column names) as quoted / as strings
    

提交回复
热议问题