【问题标题】:ggplot2 figure cache with knitrggplot2图形缓存与knitr
【发布时间】:2012-03-14 20:06:22
【问题描述】:

我有以下代码按原样工作,但在 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 中......它可以正常工作。

标签: r ggplot2 knitr


【解决方案1】:

似乎重新定义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}

【讨论】:

  • 有趣...作为knitr的作者,我什至不知道这是如何工作的;这对我来说有点出乎意料(我以为print(p1)会带来麻烦,但事实证明并没有)。我将更接近网格图对象。谢谢你的好例子:)
  • 我认为这与尝试缓存库调用相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
相关资源
最近更新 更多