How to change knitr options mid chunk

人走茶凉 提交于 2019-11-28 05:32:05
Dieter Menne

Two questions: When you want both figures to be keep, use

```{r fig.keep='all'}

Default only keeps the unique plots (because your two plots are identical, the second one is removed; see the knitr graphics manual for details).

Global chunk options are active when the next chunk(s) open:

```{r}
opts_chunk$set(fig.width=10)
```


```{r}
opts_chunk$set(fig.width=2)
# Our figure is 10 wide, not 2
plot(1:1000)
```

```{r}
# Our figure is 2 wide, not 10
opts_chunk$set(fig.width=10)
plot(1:1000)
```

This works for me, based on hints from Yui on github.

\documentclass{article}

\begin{document}
<<setup,echo=FALSE>>=
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA, warning=FALSE,message=FALSE,fig.width=6, echo=F)
kexpand=function(){
  cat(knit(
  text=knit_expand(text=
                     "<<yfig-{{cap}}-,fig.cap='{{cap}}',results='markup',echo=FALSE,fig.height={{figheight}},out.height={{outheight}}>>=\n
                   .q\n
                   @"
  )
))}
@

<<results='asis'>>=
library(ggplot2)
.q=qplot(1:10);cap="first caption";figheight=9;outheight=90
kexpand()
.q=qplot(1:20);cap="second caption";figheight=12;outheight=160
kexpand()

@
\end{document}

So one key thing is to set progress and verbose to F otherwise they destroy the output. Then the little function kexpand expands an inline template which is typed as text as part of the function. Then you can define your plot as .q and your caption as cap, and your heights etc. You could adapt the function to control other options. Strangely, .q and the caption don't have to be parameters for the function, you can just set them in the current environment and they get picked up by the function anyway. Don't know if this is good practice or why it works but it does.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!