rgraphicsglobal-variablesknitrrnw

global.par = TRUE not working in knitr for bg in RSweave doc


I need to change the background of all tiff images produced by my R Sweave document and encountered the same problem as described here:

Respecting global options in knitr

but with par(bg = ), which supposedly is working according to a comment.

MWE:

\documentclass{article}
\begin{document}

<<setup, cache = FALSE>>=
opts_chunk$set(dev = c('pdf','tiff'))
opts_knit$set(global.par = TRUE)
par(bg='cyan')
@

<<>>=
plot (3,3)
@

\end{document}

(I'm not allowed to comment or I would have stayed on that post.)

I also tried using a hook, based on the example here: https://github.com/yihui/knitr/blob/master/inst/examples/knitr-graphics.Rnw

knit_hooks$set(par=function(before, options, envir){
if (before) par(bg='cyan')
})

but that didn't work either.

The only thing that works is to set the parameter in every chunk, for example:

<<test, dev = 'tiff'>>=
par(bg = 'cyan')
plot(3,2)
@

(I actually want a white background but it's easier to test with a color. Not my choice to use TIFF btw.)

Any ideas on what's going on?


Solution

  • The MWE presented does not imply that global.par doesn't work for bg. The reason why the plot doesn't use the specified background color is that global.par = TRUE affects only the subsequent chunks.

    Knitr's settings must be set in a chunk before any chunks which rely on those settings to be active. [source]

    You cannot rely on a global option to be apply in the chunk you set it.

    The following example demonstrates that setting the background color in a later chunk makes the plot use it:

    \documentclass{article}
    \begin{document}
    
    <<setup, cache = FALSE>>=
    opts_knit$set(global.par = TRUE)
    @
    
    <<>>=
    par(bg='cyan')
    @
    
    <<>>=
    plot (3,3)
    @
    
    \end{document}