Recently I became aware of the recordPlot command in R that lets you save figures to then use replayPlot to re-use them as necessary. This works with base R plots without issue:
my.plots <- vector('list', 5)
for (i in 1:5) {
plot(i)
my.plots[[i]] <- recordPlot()
}
pdf('Test.pdf')
for (i in 1:5) {
replayPlot(my.plots[[i]])
}
dev.off()
However, when I try to set up a similar approach with levelplot (a plot from the lattice package), I receive an error. Specifically, I get Error in recordPlot() : no current device to record from, when using something like:
my.plots <- vector('list', 5)
for (i in 1:5) {
temp <- matrix(rnorm(25), 5, 5)
levelplot(temp)
my.plots[[i]] <- recordPlot()
}
pdf('Test.pdf')
for (i in 1:5) {
replayPlot(my.plots[[i]])
}
dev.off()
How can I use a similar construction with lattice plots?
>Solution :
This is even easier with lattice plots (or any plots, e.g. ggplot output, based on grid graphics): in this case the plots themselves are R objects, and can be stored and printed later. The code is basically identical to yours, it just replaces storing the output of recordPlot() with storing the plot object itself, and replaces replayPlot() with print().
my.plots <- vector('list', 5)
for (i in 1:5) {
temp <- matrix(rnorm(25), 5, 5)
my.plots[[i]] <- lattice::levelplot(temp)
}
pdf('Test.pdf')
for (i in 1:5) {
print(my.plots[[i]])
}
dev.off()