使用ggplot和aes_string创建绘图函数

Ed *_*ine 21 r ggplot2

在Hadley Wickham的第10.3章中的ggplot2一书中,他提到了制作情节功能.我想制作许多使用刻面的类似图,但我不能引用列.如果我的所有引用都是美学的,那么我可以使用aes_string,一切正常.Facet_wrap似乎没有类似的东西.

library(ggplot2)
data(iris)
Run Code Online (Sandbox Code Playgroud)

这是我想要功能化的情节.

pl.flower1 <- ggplot(data=iris, 
                    aes_string(x='Sepal.Length', y='Sepal.Width', color='Petal.Length')) +
                                 geom_point() +facet_wrap(~Species)
Run Code Online (Sandbox Code Playgroud)

如果我不这样做,这是有效的.

flowerPlot <- function(dat, sl, sw, pl, sp){
  ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) + geom_point()
}
pl.flower2 <- flowerPlot(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length')
Run Code Online (Sandbox Code Playgroud)

"sp"应该是下面的两行?一个公式,一个字符串?也许整个方法都是错误的.

flowerPlotWrap <- function(dat, sl, sw, pl, sp){
      ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) + geom_point() +facet_wrap(sp)
    }
    pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp= ?????)
Run Code Online (Sandbox Code Playgroud)

除了答案,我会喜欢指向任何人如何解决这个问题?

mat*_*fee 19

facet_wrap期望一个公式作为它的第一个参数,所以我只是强制它as.formula,并sp以字符串形式输入:

flowerPlotWrap <- function(dat, sl, sw, pl, sp){
      ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) + 
      geom_point() +facet_wrap(as.formula(sp)) # note the as.formula
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length', 
                             sw='Sepal.Width', pl='Petal.Length', 
                             sp= '~Species')
Run Code Online (Sandbox Code Playgroud)

或者,如果我的公式总是看起来像~[columnname],我可以将其构建到flowerPlotWrap并传入列名:

flowerPlotWrap <- function(dat, sl, sw, pl, sp){
      ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) + 
      geom_point() +facet_wrap(as.formula(sprintf('~%s',sp)))
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length', 
                             sw='Sepal.Width', pl='Petal.Length', 
                             sp= 'Species')
Run Code Online (Sandbox Code Playgroud)

(对你问题中可重复的例子感到荣幸!如果每个人都提出问题以及他们能更快地得到答案).


Moo*_*per 5

以下是使用以下新功能的一些替代方案ggplot2 V3.0.0

使用字符串:

flowerPlot <- function(dat, sl, sw, pl, sp){
  ggplot(data=dat, aes(x=!!ensym(sl), y=!!ensym(sw), color=!!ensym(pl))) + 
    geom_point() +
    facet_wrap(eval(expr(~!!ensym(sp))))
}

flowerPlot(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp = 'Species')
Run Code Online (Sandbox Code Playgroud)

使用名称:

flowerPlot2 <- function(dat, sl, sw, pl, sp){
  ggplot(data=dat, aes(x=!!enquo(sl), y=!!enquo(sw), color=!!enquo(pl))) + 
    geom_point() +
    facet_wrap(eval(expr(~!!enquo(sp))))
}

flowerPlot2(iris, sl= Sepal.Length, sw=Sepal.Width, pl=Petal.Length, sp = Species)
Run Code Online (Sandbox Code Playgroud)