Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using recordPlot with lattice

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading