使用 recordPlot 与 lattice

huangapple go评论77阅读模式
英文:

Using recordPlot with lattice

问题

最近我了解到R中的recordPlot命令,它允许您保存图形,然后可以使用replayPlot在需要时重新使用它们。这适用于基本的R绘图,没有问题:

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()

然而,当我尝试使用levelplot(来自lattice包的绘图)来设置类似的方法时,我收到一个错误。具体来说,当使用以下代码时,我会得到Error in recordPlot() : no current device to record from

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()

如何在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 &lt;- vector(&#39;list&#39;, 5)
for (i in 1:5) {
    plot(i)
    my.plots[[i]] &lt;- recordPlot()
}

pdf(&#39;Test.pdf&#39;)
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 &lt;- vector(&#39;list&#39;, 5)
for (i in 1:5) {
    temp &lt;- matrix(rnorm(25), 5, 5)
    levelplot(temp)
    my.plots[[i]] &lt;- recordPlot()
}

pdf(&#39;Test.pdf&#39;)
for (i in 1:5) {
    replayPlot(my.plots[[i]])
}
dev.off()

How can I use a similar construction with lattice plots?

答案1

得分: 1

这在使用格子图(或任何图形,例如基于网格图形的ggplot输出)时更容易:在这种情况下,图形本身是R对象,可以存储并稍后打印。 代码基本上与您的代码相同,只是将recordPlot()的输出替换为存储图形对象本身,并将replayPlot()替换为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()
英文:

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 &lt;- vector(&#39;list&#39;, 5)
for (i in 1:5) {
    temp &lt;- matrix(rnorm(25), 5, 5)
    my.plots[[i]] &lt;- lattice::levelplot(temp)
}
pdf(&#39;Test.pdf&#39;)
for (i in 1:5) {
    print(my.plots[[i]])
}
dev.off()

huangapple
  • 本文由 发表于 2023年7月20日 11:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定