ggplot2图形缓存与knitr

4
我有以下代码,它在不使用cache时可以正常工作,但在使用cache=T时无法工作。更改设备也没有任何区别(默认,tikz,cairo)。
% \SweaveOpts{fig.path=cache/figure/plot-,cache.path=cache/data/data-,fig.align=center,external=TRUE,fig.show=hold,cache=TRUE,echo=FALSE,pdfcrop=TRUE}

<<message=F,fig.width=9,fig.height=6,out.width=\textwidth,cache=F>>=
grid.newpage()
pushViewport(viewport(layout = grid.layout(2,9))) 

d <- ncol(rTSc)
p <- ggplot(melt(coveig),aes(1:d,value,group=variable,col=variable))  + 
  geom_line() + labs(x="index",y="eigenvalue") + 
  opts(legend.position = "none")  
print(p, vp=viewport(layout.pos.row=1,layout.pos.col=1:4))
p <- ggplot(melt(coreig),aes(1:d,value,group=variable,col=variable)) + 
  geom_line() + labs(x="index",y="eigenvalue")
print(p, vp=viewport(layout.pos.row=1,layout.pos.col=5:9))

p <- ggplot(melt(coveig.cs),aes(1:d,value,group=variable,col=variable)) + 
  geom_line() + labs(x="index",y="cumulative eigenvalue") + 
  opts(legend.position = "none")
print(p, vp=viewport(layout.pos.row=2,layout.pos.col=1:4))
p <- ggplot(melt(coreig.cs),aes(1:d,value,group=variable,col=variable)) + 
  geom_line() + labs(x="index",y="cumulative eigenvalue")
print(p, vp=viewport(layout.pos.row=2,layout.pos.col=5:9))
@ 

为什么会这样呢?你有什么想法吗?
谢谢!

当我按照你的方式运行它(重新打印 p),它就无法正常工作。但是,当我将每个绘图保存到新变量 p1、p2、p3 等中运行时,它可以无问题地工作。 - Brandon Bertelsen
1个回答

5

看起来重新定义 p 是导致缓存出问题的原因。尝试将图片保存为单独的图形,然后逐个推送到视口中。(这也可以使代码更清晰)。

\documentclass[12pt]{article}
\title{Example}

\begin{document}

<<loading,echo=F>>=
library(ggplot2)
library(gridExtra)
@

\section{This is a Section}

<<message=F,fig.width=9,fig.height=6,out.width=\textwidth,cache=T>>=
x <- rnorm(100)
y <- runif(100)
dat <- data.frame(x,y)

grid.newpage()
pushViewport(viewport(layout = grid.layout(2,9))) 

p1 <- ggplot(dat, aes(x,y)) + geom_point()
p2 <- ggplot(dat, aes(y,x)) + geom_point()

print(p1, vp=viewport(layout.pos.row=1,layout.pos.col=1:9))
print(p2, vp=viewport(layout.pos.row=2,layout.pos.col=1:9))
@

\end{document}

10
有趣...作为knitr的作者,我甚至不知道这是如何工作的;这对我来说有些出乎意料(我认为print(p1)会带来麻烦,但事实证明它没有)。我将更仔细地查看grid plot对象。感谢您提供的优秀示例 :) - Yihui Xie
我认为这与尝试缓存库调用的思路类似。 - Brandon Bertelsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接