I cannot figure out why the following function is not working. I will create data for the example if necessary. Please let me know. But it will take a lot of time and hence, I wanted to ask first without the data, in case, the problem is obvious that you can see without the data.
Please see the code below. If I use the function
plotReturns(8, "1930-01-01", "1940-12-31", "savehere.pdf")
the file savehere.pdf is created, but I cannot open it. I get an error saying
There was an error opening this document. This file cannot be opened because it has no pages.
But, if instead of using the function, I manually go through each step in that function code (replacing the variable names by the values used above as arguments) then file savehere.pdf is created fine and I can open it.
So, it appears there is nothing wrong with any of my specific commands. But then why does the function not work when called as a function?
Thanks for your help.
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()
}
It’s in the FAQ.
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f
You need to
printlattice and ggplot objects when you are inside functions. They are both types of “grid graphics” which typically get built up in sections of commands rather than always working as side-effects on graphics devices. That model is especially pertinent for ggplot where it is typical to add features using the “+” plotting operator. However, Lattice graphics function also return lists so they, too, can be appended-to with functions liketrellis.focusandupdate.trellis