A previous post provided a solution to iteratively store plots in R: see … iteratively in R… . I had a similar problem and after reading and implementing the solutions provided by the post I am still unable to solve my problem.
The previous post provided the following code:
# Create a list to hold the plot objects.
pltList <- list()
for( i in 2:15 ){# Get data, perform analysis, ect.
# Create plot name.
pltName <- paste( 'a', i, sep = '' )# Store a plot in the list using the
name as an index.
pltList[[ pltName ]] <- plot()}
The following is my code implementation:
a <- list.files("F:.../4hrs", pattern='.csv')
pltList <- list()
i=1
for (x in a) {
myfiles <- read.csv(a, header=TRUE, as.is=TRUE, nrows=2500)
h <- hist(data, plot=F)
# perform analysis, ect.
pltName <- paste('a', formatC(i, width=2, flag='0'), sep='')
pltList[[ pltName ]] <- plot(h)
i <- i+1
}
pltName does produce a list of names but pltList is of length zero.
I am not sure why pltList is not being assigned the plots.
What I eventually want to do is create a pltList with multiple plots contained therein. Then plot those plots in par(mfrow=c(2,1)) style and export as a .pdf.
I should mention that the above works for
pltList[[ pltName ]] <- xyplot(h)
but then I am unable to plot multiple plots in the style of par(mfrow=c(2,1)).
Any suggestions are appreciated.
In the original question you referenced and my answer to it,
plot()was used as an abstract placeholder for a plotting function that returned an object and not a literal call to the R functionplot. Most functions that return graphics objects are based on the ‘grid’ package such asxyplotfrom the lattice package orqplotfrom ggplot2.Sorry for the confusion, I should have made this point clear in my answer, but I did not as the asker of the question was already aware of it.
Base graphics functions such as
histandplotrender directly to output and do not return any objects that can be used to recreate the plot at a later time which is why you are ending up with a list of length zero.In order to use this approach you will have to trade usage of the
histfunction for something that returns an object. Using ggplot2, you could do something like the following in your loop:I have edited my answer to the previous question to make it clear that the use of
plot()in my example is not an actual call to the R function of the same name.