2011-12-30 3 views
1

私は次の機能がうまくいかない理由を理解できません。必要に応じて、この例のデータを作成します。私にお知らせください。しかし、それは多くの時間がかかるので、私は最初にデータなしで尋ねたがっています。その場合、データがなくても問題は明らかです。プロットコマンドを関数の一部として定義し、カスタム定義関数を使用してプロットすることはできますか?

下記のコードをご覧ください。私は機能

plotReturns(8, "1930-01-01", "1940-12-31", "savehere.pdf")

を使用している場合は、ファイルsavehere.pdf作成されますが、私はそれを開くことができません。

この文書を開くのにエラーがありました。このファイルはページがないため開けません。

しかし、代わりに関数を使用すると、私は手動でその関数のコードの各ステップを経る場合(引数として上記使用された値によって変数名を置き換える)、その後savehere.pdfファイルを微作成され、私はそれを開くことができます。

私の特定のコマンドには何も問題はないようです。しかし、なぜ関数は関数として呼び出されても機能しないのですか?

ありがとうございました。

plotReturns = function(decileValue, startDate, endDate, fileName) { 
    # Keep data from specific decile 
    specificdecile <- merged.data[merged.data$decile_correct == decileValue,] 

    #filter the data to get rows within the specified dates 
    specificdecileAndYears <- specificdecile[ 
          ((specificdecile$rdate >= as.Date(startDate)) & 
           (specificdecile$rdate <= as.Date(endDate))),] 
    #keep the necessary columns:rdate, decile_correct, vwret_bottomup, vwret_CRSP 
    specificdecileAndYears <- specificdecileAndYears[c("rdate", "decile_correct", 
                "vwret_bottomup", "vwret_CRSP")] 
    # Melt the data for plotting 
    melted.data <- melt(specificdecileAndYears, id=c("rdate","decile_correct")) 

    # Use melted data for plotting 

    # Set the plot title 
    title <- paste("Plot for decile", decileValue) 

    # Specifing colors to be used for line plots 
    myColors <- c("steelblue", rgb(1,0.5,0.3,0.5)) 
    fileName <- fileName 

    pdf(fileName, width=8, height=5) 

    # scale_color_manual is to use custom colors specified in myColors above. 
    # The first argument of scale_color_manual specifies the title of the legend, 
    # which is set to empty here. 
    ggplot(melted.data, aes(x=rdate, y=value, color=variable)) + geom_line() + 
     opts(legend.position=c(0.85,0.2), legend.background=theme_rect(col=0), title=title) + 
     scale_color_manual("", values=myColors) + 
     ylab("Return") + xlab("") 

    # turn device off 
    dev.off() 
} 
+2

これはよくある質問です。関数内からggplotまたはlatticeグラフィックを明示的に_print_しなければなりません。すなわち、 'p < - ggplot(...); print(p) '。 – joran

+0

ありがとう、ジョラン。あなたの応答を感謝します。 – Curious2learn

答えて

5

よくある質問です。

http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f

あなたが内部機能しているときには、print格子とggplotオブジェクトにする必要があります。それらは、グラフィックデバイスの副作用として常に働くのではなく、コマンドのセクションで通常構築される「グリッドグラフィックス」の両方のタイプです。このモデルは、プロット演算子を使ってフィーチャを追加するのが典型的なggplotに特に適しています。しかし、ラティスのグラフィックス関数もリストを返すので、trellis.focusupdate.trellisのような関数を追加することができます。

+0

恐ろしい!本当にありがとう。あなたのポストであなたが参照しているFAQにリンクしていただけますか? – Curious2learn

+2

@ Curious2learnこれは、CRANのウェブサイト[ここ](http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis -graphics-not- work_003f) – joran

+0

faqパッケージが必要です... 2012年の希望リスト – baptiste

関連する問題