英文:
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 <- 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?
答案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 <- 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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论