Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

r - Making plot functions with ggplot and aes_string

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 refer to a column. If all my references are in aesthetics then I can use aes_string and everything works. Facet_wrap seems not to have an analogue.

library(ggplot2)
data(iris)

This is the plot I want to functionalize.

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

This works if I do not facet.

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

What should "sp" be two lines below? A formula, a string? Maybe the whole aproach is wrong.

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

In addition to an answer I would love pointer on how anyone approaches this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...