私は次の機能がうまくいかない理由を理解できません。必要に応じて、この例のデータを作成します。私にお知らせください。しかし、それは多くの時間がかかるので、私は最初にデータなしで尋ねたがっています。その場合、データがなくても問題は明らかです。プロットコマンドを関数の一部として定義し、カスタム定義関数を使用してプロットすることはできますか?
下記のコードをご覧ください。私は機能
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()
}
これはよくある質問です。関数内からggplotまたはlatticeグラフィックを明示的に_print_しなければなりません。すなわち、 'p < - ggplot(...); print(p) '。 – joran
ありがとう、ジョラン。あなたの応答を感謝します。 – Curious2learn