1

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?

Community
  • 1
  • 1
jtr13
  • 1,225
  • 11
  • 25
  • Please add a reproducible example where `global.par` doesn't work for `bg`. On your hook: Did you "activate" the hook, i.e. did you use `par = TRUE` as chunk option? – CL. Mar 01 '16 at 14:37
  • No, that's it! I didn't activate the hook! Thank you!!! (I'm including the example for global.par anyway.) – jtr13 Mar 01 '16 at 14:57

1 Answers1

1

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}
CL.
  • 14,577
  • 5
  • 46
  • 73
  • Aha. That works. Many, many thanks! (I upvoted the answer but it doesn't view publicly.) – jtr13 Mar 01 '16 at 15:37