2012-04-04 14 views
18

第10.3章のHadley Wickhamのggplot2の本では、プロット関数の作成を暗に示しています。ファセットを使用する類似のプロットをたくさん作成したいが、列を参照することはできない。すべての私の参照が美学の中にあるなら、私はaes_stringを使うことができ、すべてが機能します。 Facet_wrapはアナログを持っていないようです。ggplotとaes_stringを使ったプロット関数の作成

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) 

これは機能しない場合に機能します。

「sp」は2行下にする必要がありますか?数式、文字列ですか?たぶん全体の問題は間違っています。

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

回答に加えて、誰かがどのようにこの問題に近づいているかについてのポインタが大好きです。

+0

この問題を解決する方法については、まず[StackOverflow](http://stackoverflow.com/questions/8043247/writing-r-functions-with-optional-arguments)をチェックしてください。 :) – joran

+0

こちらもお尋ねください:http://stackoverflow.com/questions/11028353/passing-string-variable-facet-wrap-in-ggplot-using-r –

答えて

15

facet_wrap

flowerPlotWrap(iris, sl='Sepal.Length', sw='Sepal.Width', pl='Petal.Length', sp='Species')は、最初の引数として式を想定していたので、私はちょうど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

明確な答えをありがとう。 facet_wrapが数式を期待していることはどうでしたか? –

+0

'?facet_wrap'を見ると' facet_wrap(facets、...) 'と' facets:数式を指定する数式 'と書かれています。 –

1

私がちょうどsp='Species'、つまり面取りしたい変数の名前を使用した場合、あなたの機能はそのまま私にとってうまく機能しました。

enter image description here

関連する問題