首页 文章

使用ggplot和aes_string创建绘图函数

提问于
浏览
18

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

library(ggplot2)
data(iris)

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

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

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

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

“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= ?????)

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

3 回答

  • 16

    以下是使用 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')
    

    使用名称:

    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)
    
  • 1

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

    或者,如果我的公式总是看起来像 ~[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')
    

    (对你问题中可重复的例子表示赞赏!如果每个人都提出问题以及他们会更快地得到答案) .

  • 0

    如果我刚刚使用 sp='Species' ,即你想要面对的变量的名称,你的功能对我来说没有修改 .

    flowerPlotWrap(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp='Species')

    enter image description here

相关问题