Making plot functions with ggplot and aes_string

后端 未结 3 2059
眼角桃花
眼角桃花 2020-12-01 05:41

In Hadley Wickham\'s ggplot2 book in chapter 10.3, he alludes to making plot functions. I want to make many similar plots that use faceting, but I cannot r

相关标签:
3条回答
  • 2020-12-01 06:02

    Here are some alternatives using new features from ggplot2 V3.0.0

    Using strings :

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

    Using names :

    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)
    
    0 讨论(0)
  • 2020-12-01 06:23

    facet_wrap expects a formula as its first argument, so I'd just coerce it with as.formula, and feed in my sp as a string:

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

    Alternatively if my formula was always going to look like ~[columnname], I could just build that in to flowerPlotWrap and pass in the column name:

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

    (kudos to the reproducible example in your question! If everyone asked questions as well as that they'd get answers much quicker).

    0 讨论(0)
  • 2020-12-01 06:25

    Your function worked fine for me unmodified if I just used sp='Species', i.e. the name of the variable you want to facet by.

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

    enter image description here

    0 讨论(0)
提交回复
热议问题