我希望能够在knitr中打印出非预定的情节列表。我我能够做到这一点,但还有一些皱纹可以解决。即:
1)如何在每个绘图之前的每个页面上抑制列表索引(如[[2]])?使用echo = FALSE不做任何事情。
2)是否可以设置每个情节的大小?我已经尝试在块之外设置一个大小变量,但这只允许我使用一个值而不是每个绘图的不同值。
我将这个问题作为一个问题,因为他们似乎在讲同一课,即制作一份情节清单。
一些示例代码:
\documentclass{article}
\usepackage[margin=.5in, landscape]{geometry}
\begin{document}
<<diamond_plots, echo = FALSE, results = 'hide'>>==
library(ggplot2)
diamond_plot = function(data, cut_type){
ggplot(data, aes(color, fill=cut)) +
geom_bar() +
ggtitle(paste("Cut:", cut_type, sep = ""))
}
cuts = unique(diamonds$cut)
plots = list()
for(i in 1:length(cuts)){
data = subset(diamonds, cut == cuts[i])
plots[[i]] = diamond_plot(data, cuts[i])
}
height = 3
@
<<print_plots, results='asis', echo=FALSE, fig.width=10, fig.height=height>>=
plots
@
\end{document}
这些情节的PDF看起来像这样:
答案 0 :(得分:10)
1)如何在每个绘图之前的每个页面上抑制列表索引(如[[2]])?使用echo = FALSE不会做任何事情。
分别在列表中绘制每个元素(lapply
)并隐藏lapply
(invisible
)的输出:
invisible(lapply(plots, print))
2)是否可以在渲染时为每个绘图设置大小?我已经尝试在块之外设置一个大小变量,但这只是让我使用一个值而不是每个绘图的不同值。
是。通常,当您将向量传递给与图相关的块选项时,i
th 元素将用于i
th 图。这适用于“特定于图形”的选项,例如fig.cap
,fig.scap
,out.width
和out.height
。
但是,其他图形选项是“特定于设备”。要理解这一点,请务必查看option dev
:
dev
:将用作图形设备的函数名称,用于记录选项dev
,fig.ext
,fig.width
,{{1} }和fig.height
可以是矢量(较短的将被回收),例如dpi
为同一个图创建了两个文件:<<foo, dev=c('pdf', 'png')>>=
和foo.pdf
将向量传递给“特定于数字”选项foo.png
时,out.height
th 元素被用于i
th plot ,将向量传递给“特定于设备”选项的结果是i
th 元素用于{{1 th 设备。
因此,生成动态大小的绘图需要对块进行一些黑客攻击,因为一个块无法生成具有不同i
设置的绘图。以下解决方案基于i
示例`075-knit-expand.Rnw和this post on r-bloggers.com(解释this answer on SO)。
解决方案的想法是使用块模板并使用适当的表达式扩展模板值以生成块,然后生成具有正确fig.height
设置的图。扩展模板将传递给knitr
以评估块:
fig.height
使用knit
扩展模板,用相应的值替换\documentclass{article}
\begin{document}
<<diamond_plots, echo = FALSE, results = "asis">>==
library(ggplot2)
library(knitr)
diamond_plot = function(data, cut_type){
ggplot(data, aes(color, fill=cut)) +
geom_bar() +
ggtitle(paste("Cut:", cut_type, sep = ""))
}
cuts = unique(diamonds$cut)
template <- "<<plot-cut-{{i}}, fig.height = {{height}}, echo = FALSE>>=
data = subset(diamonds, cut == cuts[i])
plot(diamond_plot(data, cuts[i]))
@"
for (i in seq_along(cuts)) {
cat(knit(text = knit_expand(text = template, i = i, height = 2 * i), quiet = TRUE))
}
@
\end{document}
中的表达式。
对于knit_expand
电话,使用{{}}
非常重要。否则,knit
将使用日志信息污染主文档。
使用quite = TRUE
对于避免隐含输出的隐式knit
非常重要。出于同样的原因,“外部”块(cat
)使用print
。
答案 1 :(得分:0)
您需要访问各个列表元素,否则print将始终打印出索引。
不确定这是否是最干净的答案,但您可以将它们打印出来。
> print(plots)
[[1]]
[[2]]
[[3]]
[[4]]
[[5]]
> for(x in plots){print(x)}
但我没有在tex中尝试这个,只是控制台。